【问题标题】:Not showing md-hint using email validator in Data-Driven forms未在数据驱动表单中使用电子邮件验证器显示 md-hint
【发布时间】:2017-07-30 22:49:36
【问题描述】:

当电子邮件无效但未在我的 html 中显示时,我尝试显示 md 提示。

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};
    }
}

感谢您的帮助!

【问题讨论】:

  • email 模板中的变量是 HTMLInputElement 实例。您需要使用 FormControl 实例来检查 myForm.get('email') 之类的错误

标签: angular data-driven angular-forms


【解决方案1】:

我想你错过了插入 formGroup

你应该在&lt;md-input-container class="col-md-6 md-icon-left"&gt;[formGroup]='myForm'

Augury chrome 扩展可以帮助您和您的表单验证。

【讨论】:

    【解决方案2】:

    就像@yurzui说的,

    模板中的电子邮件变量是 HTMLInputElement 实例。您需要使用 FormControl 实例来检查诸如 myForm.get('email') 之类的错误

    所以你需要这样做:

    <md-hint *ngIf="!myForm.get('email').pristine && myForm.hasError('noEmail', 'email')">
      Invalid mail address
    </md-hint>
    

    如果您使用的是 Angular 4,您可以使用内置的验证器 email 并完全跳过自定义验证器。 Validators.componse 也是“旧的”Angular v 2 语法。所以你可以这样做:

    email: ['', [Validators.required, Validators.email]]
    

    当然还有模板中相应的错误信息:

    myForm.hasError('email', 'email')
    

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2021-03-06
      相关资源
      最近更新 更多