自定义验证器无法以Angular反应形式正常工作

时间:2019-07-07 23:23:30

标签: angular typescript validation angular7 angular-reactive-forms

是Angular的新手,并尝试添加自定义电子邮件验证器,该验证器将进入我的服务器并检查电子邮件地址是否已在使用中。

但是似乎无法在表单上显示错误消息。 这是我尝试打入服务器之前进行测试的方式。

仅供参考-“ emailMatchValidator()”已被调用,但我无法在表单上显示任何错误消息!

也许我应该尝试.touch以外的其他方式!

ngOnInit() {
    this.createRegisterForm();
  }

createRegisterForm() {
  this.registerForm = this.fb.group({
    gender: ['male'],
    email: ['', [Validators.required, Validators.email]],
    username: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],
    knownAs: ['', Validators.required],
    dateOfBirth: [null, Validators.required],
    city: ['', Validators.required],
    country: ['', Validators.required],
    password: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(8)]],
    confirmPassword: ['', Validators.required]
  }, {
    validator: [this.passwordMatchValidator, this.emailMatchValidator]
  });
}

emailMatchValidator(g: FormGroup) {
  return g.get('email').value !== 'emailaddress@gmail.com' ? null : {
    emailExists: true
  };
}
<div class="form-group">
                      <input type="email" 
                        [ngClass]="{'is-invalid': registerForm.get('email').errors && registerForm.get('email').touched}
                          || registerForm.get('email').touched && registerForm.hasError('emailExists')"
                        class="form-control" 
                        formControlName="email" 
                        placeholder="Email">
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('required')">
                          Email is required
                        </div>
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('email')">
                          Invalid email address
                        </div>
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('emailExists')">
                            Email address already in use
                          </div>
                    </div>

1 个答案:

答案 0 :(得分:1)

进行一些更改:

  • 您已将验证应用于完整的表单,我仅将其更改为电子邮件字段email: ['', [Validators.required, Validators.email, this.emailMatchValidator]],;

  • 在屏幕上添加了电子邮件字段值和电子邮件字段状态,以查看正在执行的验证

  • 在电子邮件字段中输入任何内容并转移焦点以使验证生效

相关的 HTML

    <form class="form-group" [formGroup]='registerForm'>
        <input type="email" 
                        [ngClass]="{'is-invalid': registerForm.get('email').errors && registerForm.get('email').touched}
                          || registerForm.get('email').touched && registerForm.hasError('emailExists')"
                        class="form-control" 
                        formControlName="email" 
                        placeholder="Email">
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('required')">
                          Email is required
                        </div>
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('email')">
                          Invalid email address
                        </div>
                        <div class="invalid-feedback" *ngIf="registerForm.get('email').touched && registerForm.get('email').hasError('emailExists')">
                            Email address already in use
                          </div>
                    </form>

<hr/>
                    <b>email value:</b> {{registerForm.controls.email.value}} <br/>
                    <b>email status:</b> {{registerForm.controls.email.status}}

相关的 TS

import { Component } from '@angular/core';
import { FormBuilder, Validators, FormGroup, AbstractControl } from '@angular/forms'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  constructor(private fb: FormBuilder) { }
  registerForm;

  ngOnInit() {
    this.createRegisterForm();
    console.log(this.registerForm);
  }

  createRegisterForm() {
    this.registerForm = this.fb.group({
      gender: ['male'],
      email: ['', [Validators.required, Validators.email, this.emailMatchValidator]],
      username: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],
      knownAs: ['', Validators.required],
      dateOfBirth: [null, Validators.required],
      city: ['', Validators.required],
      country: ['', Validators.required],
      password: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(8)]],
      confirmPassword: ['', Validators.required]
    }
      /*, {
          validator: [this.passwordMatchValidator, this.emailMatchValidator]
        }
        */
    );
  }

  passwordMatchValidator() {
    /* some implementation */
  }

  emailMatchValidator(control: AbstractControl) {
    if (control.value !== 'emailaddress@gmail.com') {
      return false;
    } else {
      return { emailExists: true };
    }
  }

}

工作stackblitz here