我试图在电子邮件无效但是没有显示在我的HTML中时显示md-hint。
HTML
<form [formGroup]="myForm" (ngSubmit)="onSignup()">
<md-input-container class="col-md-6 md-icon-left">
<md-icon class="material-icons">mail_outline</md-icon>
<input formControlName="email" mdInput #email type="email" name="email" class="form-control" placeholder="Email">
<md-hint *ngIf="!email.pristine && email.errors != null && email.errors['noEmail']">Invalid mail address</md-hint>
</md-input-container>
</form>
component.ts
myForm: FormGroup;
error = false;
errorMessage = '';
constructor(private fb: FormBuilder,
private authService: AuthService,
rv: RutValidator) {
this.myForm = this.fb.group({
email: ['', Validators.compose([
Validators.required,
this.isEmail
])],
});
}
isEmail(control: FormControl): {[s: string]: boolean} {
if (!control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
return {noEmail: true};
}
}
感谢您的帮助!
答案 0 :(得分:0)
我想你错过了插入formGroup
。
你应该在[formGroup]='myForm'
写一下<md-input-container class="col-md-6 md-icon-left">
。
Augury chrome扩展可能会帮助您和您的表单验证。
答案 1 :(得分:0)
就像@yurzui说的那样,
模板中的电子邮件变量是HTMLInputElement实例。您需要使用FormControl实例来检查myForm.get之类的错误(&#39; email&#39;)
所以你需要这样做:
<md-hint *ngIf="!myForm.get('email').pristine && myForm.hasError('noEmail', 'email')">
Invalid mail address
</md-hint>
如果您使用的是Angular 4,则可以使用内置的Validator email
并完全跳过自定义验证器。同样Validators.componse
是&#34; old&#34; Angular v 2语法。所以你可以这样做:
email: ['', [Validators.required, Validators.email]]
当然还有模板中的相应错误消息:
myForm.hasError('email', 'email')