0
votes

I implemented the email validation through the tutorials. The problem is Email validation accepts something like "asd@asd" which is not a valid mail.

Secondly i get the error "ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead. " tried all the answers on stackoverflow but none of them worked. What am i doing wrong ?

  this.loginForm = this.formBuilder.group({
          email: ['', [Validators.required, Validators.email,
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]],
        });

And the template :

 <input class="form-control" formControlName="email" type="text"[(ngModel)]="username" name="username" placeholder="E-mail"
               [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
        <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
          <div *ngIf="f.email.errors.required">Email is required</div>
          <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
        </div>
1
As already you're using formControlName in your <input> tag. Don't use ngModel - Chaitanya
You shouldn't be using ngModel in form group. How ever if you want to use it for some reason, you have to declare it as a standalone. [ngModelOptions]="{standalone: true}" - Dino
[ngModelOptions]="{standalone: true}" didnt change anything " Can't bind to 'ngModelOptions' since it isn't a known property of 'input'." - Tolga Tamer
Like the first comment said. Either use ngModel or formcontrolname. I suggest the last option, as it is giving u much more options than simply bind to ngModel. - sagat
if i wont use ngModel , how would i reach the email value ? i tried get email() { return this.loginForm.get('email');} but not working - Tolga Tamer

1 Answers

3
votes

You may use the formControlName directive alone to bind the email control.

<form [formGroup]= 'loginForm'> 
   <input id='email'  class="form-control" formControlName="email" 
        type="text" placeholder="E-mail" 
        [ngClass]="{ 'is-invalid': submitted && email.errors }" /> 
   <div *ngIf="submitted && email.errors" class="invalid-feedback"> 
       <div *ngIf="email.errors.required">Email is required</div>
       <div *ngIf="email.errors.email">
          Email must be a valid email address
       </div>
   </div>
</form>

Alternatively, you can get the control instance using the loginForm.get('email') method and use the loginForm.get('email').errors object to display error messages.