如何触摸使用角度2中的模式验证电子邮件控制?

时间:2017-01-29 17:07:44

标签: angular typescript

我想询问如何访问电子邮件模式错误,以便在角度2中通过hasError进行验证,以便我可以在输入字段上应用invalid类。 以下是registration.component.html代码:

<div class="input-field col s6">
    <input id="Email" type="email" [formControl]="myCustomForm.controls['email']" [ngClass]="{invalid: myCustomForm.controls['email'].touched && myCustomForm.controls['email'].hasError('required')}">
    <label for="Email">Email</label>
</div>

下面是registration.component.ts代码:

constructor(private fb: FormBuilder, private ASD: AppStartupData, private af: AngularFire) {
this.registration_id;
this.svc_AppStartupData = ASD;
this.myCustomForm = fb.group({
  "first_name": ['', Validators.required],
  "middle_name": [''],
  "last_name": ['', Validators.required],
  "gender": ['', Validators.required],
  "email": ['', Validators.compose([Validators.required, Validators.pattern("^[a-zA-Z0–9_.+\\-\\]+@[a-zA-Z0–9-]+.[a-zA-Z0–9\\-\\.]+$")])],
  "password": ['', Validators.required],
  "telephone": ['', Validators.required],
  "cities": ['', Validators.required],
  "address": ['', Validators.required],
  "dob": ['', Validators.required]
});
}

1 个答案:

答案 0 :(得分:0)

根据我的问题。我找到了如何验证角度2 ontouched的电子邮件控制的方式。下面是我的代码,我在我的课程中使用了registration.component.ts

customValidation(control: FormControl): { [s: string]: boolean } {
    if (!control.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
        return { invalidSku: true };
    }
}

在我的registration.component.html中,我把:

[ngClass]="{invalid: myCustomForm.controls['email'].touched && myCustomForm.controls['email'].hasError('invalidSku')}"