【问题标题】:angular validate that a pair of form fields are empty or both are filled角度验证一对表单字段是否为空或两者都已填充
【发布时间】:2019-08-22 11:42:12
【问题描述】:

我创建了一个包含 4 到 5 个字段的学生表单。对于联系电话,我有 2 个字段,国家代码和电话号码。如果用户只输入两个字段之一,即输入国家代码但没有输入电话号码,我想抛出错误,反之亦然。但是,如果两个字段都留空,则它是有效的,因为它们都是非强制性字段。我不知道我怎么能做到这一点。请帮忙。提前致谢。

这是我的模板:

<mat-form-field >
<input matInput type="number"   formControlName="countryCode" placeholder="Country Code(+)" name="countryCode" class="form-control" id="countryCode">
</mat-form-field>
<mat-form-field >
<input matInput type="number" formControlName="phnNumber" placeholder="Phone Number" name="phnNumber" class="form-control" id="phnNumber">
</mat-form-field>

我的表单组:

this.addForm = this.formBuilder.group({

      studentName: ['', Validators.required],
      phnNumber: new FormControl(''),
      countryCode: new FormControl(''),
    });

【问题讨论】:

    标签: javascript angular typescript validation


    【解决方案1】:

    您可以创建一个自定义验证器,将其放在FormGroup 上作为一个整体而不是单个控件。您对FormBuilder 的调用变为:

    this.addForm = this.formBuilder.group({
    
          studentName: ['', Validators.required],
          phnNumber: new FormControl(''),
          countryCode: new FormControl(''),
        }, { validators: myFormValidator });
    

    然后您创建一个验证器(在同一个文件或其他地方并导出):

    export const myFormValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
      const phnNumber = control.get('phnNumber').value;
      const countryCode = control.get('countryCode').value;
    
      if (phnNumber && !countryCode || countryCode && !phnNumber) {
        return { 'phoneNumberError': true };
      } else {
        return null;
      }
    };
    

    这样,自定义验证器可以从整个组中获取所需的内容,而不是需要单独验证控件。

    【讨论】:

    • 这不会按预期工作,因为您需要比较控件的值,而不是控件是否存在
    • 已编辑以提取值,感谢您发现!
    • 这也是我的建议,我投了赞成票。我对这种风格的唯一问题是将控件从表单组中取出的魔术字符串(不确定是否有更好的方法),但这就是生活。我还将控件命名为 formGroup。我还建议您将这 2 个控件放在自己的表单组中
    • 是的,这个很棒
    • 我收到错误简写属性“myFormValidator”的范围内不存在任何值。要么声明一个,要么提供一个初始化器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多