Angular4自定义在单个字段中使用多个mat-error验证FormGroup中的formFileds数组,而不显示错误消息

时间:2017-10-27 06:54:02

标签: angular angular-material2

“@ angular / forms”:“^ 4.4.6”,“@ angular / material”:“^ 2.0.0-beta.12”

尝试验证表单组中两个字段的数组,比较它们的范围,该范围应该在左侧值和右侧之间以及数字之间。数字正在工作,但是使用自定义验证错误进行范围检查,而不显示该特定字段的mat-error消息。

喜欢

  

* ngIf = “xxxDismissForm.get( 'xxx.value.1.value')。hasError( 'betweenRangeIncorrect')”

根据自定义验证条件设置为 true / false 并在模板中打印但是md-error字段消息未显示...

是mat-error的错误还是在我找不到的不合适的字段中设置了hasError。任何帮助都会很棒

Html模板:

<div fxLayout="row">
          <mat-form-field formGroupName="0" class="m-t-7">
            <input [required]="xxxDismissForm.get('xxx.include').value === true" qa-name="eventIdValue1" formControlName="value"
              matInput type="number" placeholder="XXX" i18n-placeholder="XXX" (keypress)="validationService.checkIfProducesNumber($event)">
            <mat-error *ngIf="xxxDismissForm.get('xxx.value.0.value').hasError('pattern')" i18n="Field must be an integer error message">
              This field must be a positive integer
            </mat-error>
          </mat-form-field>

          <span class="event-id-connector">And</span>

          <mat-form-field formGroupName="1" class="m-t-7">
            <input [required]="autoDismissForm.get('xxx.include').value === true" qa-name="eventIdValue2" formControlName="value"
              matInput type="number" placeholder="XXX" i18n-placeholder="XXX" (keypress)="validationService.checkIfProducesNumber($event)">

      //This Mat-error works
            <mat-error *ngIf="xxxDismissForm.get('xxx.value.1.value').hasError('pattern')" i18n="Field must be an integer error message">
              This field must be a positive integer
            </mat-error>

      //This Mat-error not working but if is set as true/false based on condition         
    <mat-error *ngIf="xxxDismissForm.get('xxx.value.1.value').hasError('betweenRangeIncorrect')" i18n="left side of the range should be lower than the right side">
              Left side of the range should be lower than the right side
            </mat-error>


          </mat-form-field>
        </div>

我的表单组件:

xxxDismissForm = this.formBuilder.group({

xxx: this.formBuilder.group({
  include: [false],
  operator: [{ value: '', disabled: true }],
  value: this.formBuilder.array([
    this.formBuilder.group(
      { value: [{ value: null, disabled: true }, [Validators.pattern(Constants.Validation.ONLY_NUMBER_REGEX)]] }
    ),
    this.formBuilder.group(
      { value: [{ value: null, disabled: true }, Validators.pattern(Constants.Validation.ONLY_NUMBER_REGEX)] }
    )
  ])
}, {validator: FormValidationService.betweenValidator('value')}), 
// Validation is called but value is set true/ false but error message is not displayed
  });

验证服务:

@Injectable()
export class FormValidationService {

static betweenValidator(controlName: string) {
return (group: FormGroup): { [key: string]: any } => {
  const control1 = group.controls[controlName].value[0];
  const control2 = group.controls[controlName].value[1];

  if (control1.value > control2.value) {
    group.controls[controlName].setErrors({'betweenRangeIncorrect': true});
    return {'betweenRangeIncorrect': true};
  }
  group.controls[controlName].setErrors(null);
  return null;
};
}
}

1 个答案:

答案 0 :(得分:1)

这可以通过自定义错误状态匹配器来解决。默认情况下,仅当实际表单控件无效时才会显示mat-errors。他们没有考虑对父表单组的任何验证。

试试这个,

<input matInput formControlName="value" [errorStateMatcher]="groupErrorMatcher">

groupErrorMatcher = {
  isErrorState(control) => {
    // where xxx is the form group that has the comparison validator on it
    return (control.invalid || this.xxx.invalid) && (control.dirty || control.touched);
  }
}

了解更多in the docs