为什么我的formGroup验证器不能按预期工作?

时间:2017-07-20 13:32:47

标签: angular validation

我正在尝试进行表单验证并遇到一些问题,如果我使用这样的角度电子邮件验证器:

<input type="email" class="mail" email name="emailField"  [(ngModel)]="email" #emailField="ngModel">

并将其放入formGroup:

<form  [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >

    <input type="email" class="mail" email name="emailField"  [(ngModel)]="email" #emailField="ngModel">
        <div  class="emailinvalid" *ngIf="emailField.invalid && emailField.touched">
          <span  *ngIf="emailField.hasError('email')">
            Please enter the correct email, this email not valid.
          </span>
        </div>
          <br>
  </form>

以这种方式电子邮件验证不起作用,所以我正在寻找解决方法,这是我的代码:

export class ContactComponent  {


    myForm: FormGroup;
    email: string;
    username: string;
    surname: string;
    message: string;

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'username':  ['', Validators.required],
      'surname': ['', Validators.required],
      'message': ['', Validators.required],

    });
  }
 }

usernamesurname以及我在上面的表单(formGroup)中使用的其他输入,我只是将其删除以清除代码中的代码。

3 个答案:

答案 0 :(得分:30)

你似乎有一个奇怪的模板和反应形式的混合。我建议您使用被动表单和内置验证器email,同时删除任何ngModel

constructor(private fb: FormBuilder) {
  this.myForm = fb.group({
    username:  ['', Validators.required],
    surname: ['', Validators.required],
    message: ['', Validators.required],
    email: ['', Validators.email]
  });
}

然后模板看起来像这样:

<form  [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >  
  <input formControlName="username" >
  <!-- more fields here -->
  <input formControlName="email" >
  <span *ngIf="myForm.hasError('email', 'email') && myForm.get('email').touched">
    Please enter the correct email, this email not valid.
  </span>
</form>

DEMO (仅为了清楚地显示验证者,我已删除了touched

答案 1 :(得分:5)

您可以拥有validator.ts文件

const pureEmail = /^(([^<>()\[\]\\.,;:\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,}))$/;

export const regexValidators = {
  phone: '[\+][0-9() ]{7,}$',
  email: pureEmail,
};

并在您的组件中使用,如:

this.myForm = fb.group({
   'username':  ['', Validators.required],
   'surname': ['', Validators.required],
   'message': ['', Validators.required],
   'email':   ['', [Validators.required,Validators.pattern(this.validators.email)]]    
});

答案 2 :(得分:1)

n

以上模式适用于我,因为Validators.pattern (/^(([^<>()\[\]\\.,;:\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,}))$/) 验证,直到我们输入Validators.email表示它使该字段有效。