Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my formGroup validator work as expected?

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.

like image 628
shoopik Avatar asked Jul 20 '17 13:07

shoopik


1 Answers

You seem to have an odd mix of template and reactive form. I suggest you use a reactive form and the inbuilt validator email and at the same time, remove any ngModel.

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

and the template would then look something like this:

<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 (just for clearly show the validator, I've removed the touched)

like image 58
AT82 Avatar answered Sep 21 '22 07:09

AT82