Why doesn't my formGroup validator work as expected?

Viewed 22632

I am tryng to do form validations and run into some issue, if I use angular email validator like this:

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

and put it into form by 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>

in that way email-validation doesn't work, so I am looking for the way to fix it, here is my ts code:

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],

    });
  }
 }

username, surname and other inputs I use in my form(formGroup) above, I've just cut it off to clean the code a little in example.

3 Answers
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,}))$/)

The above pattern works fine for me as Validators.email validates till we enter a @ .post that it is making the field as valid.

Related