键入

时间:2018-05-08 23:04:27

标签: angular angular-material angular-reactive-forms angular-forms

我正在处理此表单并希望在键入时进行验证。 当前的行为是我选择输入,类型,当我点击其他网站然后显示错误。我认为当我设置控制,有效和脏时它发生的错误,但我无法弄明白。

打字稿

buildForm(): void {
 this.userForm = this.fb.group({
  'email': ['', [
    Validators.required,
    Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')
  ]
  ],
  'password': ['', [
    Validators.required,
    Validators.minLength(6),
    Validators.maxLength(25)
   ]
   ],
 });
 this.userForm.valueChanges.subscribe(data => this.onValueChanged(data));
}

onValueChanged(data?: any) {
 if (!this.userForm) { return; }
 const form = this.userForm;
 for (const field in this.formErrors) {
  // clear previous error message (if any)
  this.formErrors[field] = '';
  const control = form.get(field);
  if (control && control.invalid && control.dirty) {
    const messages = this.validationMessages[field];
    for (const key in control.errors) {
      this.formErrors[field] += messages[key] + ' ';
     }
   }
  }
}

函数onValueChanged()更改此对象

formErrors = {
  'email': '',
  'password': ''
};

此对象具有验证消息。

validationMessages = {
 'email': {
  'required': 'Email is required',
  'pattern': 'Email is invalid'
 },
'password': {
  'required': 'Password is required',
  'minlength': 'Debe tener 6 caracteres como mínimo',
  'maxlength': 'Password cannot be more than 40 characters long.',
 }
};

HTML

      <mat-form-field class="example-full-width">
          <input matInput placeholder="Email" formControlName="email" required>
          <mat-error *ngIf="formErrors.email" align="start" class="form__error">
            {{ formErrors.email }}
          </mat-error>
        </mat-form-field>     
        <mat-form-field class="example-full-width">
          <input matInput placeholder="Password" type="password" formControlName="password" required>
          <mat-error *ngIf="formErrors.password" align="start" class="form__error">
            {{ formErrors.password }}
          </mat-error>
        </mat-form-field>

2 个答案:

答案 0 :(得分:3)

最新答案,但我会在此处发布,以防它对任何人有帮助。

在Angular 6+中,您可以通过onChange FormControl选项属性来调整表单验证行为,例如:

'email': ['', {
    validators: [
        Validators.required,
        Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')
    ],
    updateOn: 'change'
 }]

updateOn可以是:

change-更改后立即进行验证

blur-从字段中导航时进行验证

submit-在表单提交时进行验证

  

资料来源:
  https://angular.io/api/forms/AbstractControlOptions
  https://angular.io/guide/form-validation#note-on-performance

(我刚刚在这里回答了类似的问题:Fire validation when focus out from input in angular?

答案 1 :(得分:0)

默认情况下,触摸控件或提交表单且控件无效时,将显示表单字段错误。要更改该行为,可以使用自定义ErrorStateMatcher - 请参阅Angular Material示例Input with a custom ErrorStateMatcher