Issue
I am trying to do validations for email and password in angular with the following code but i am running into errors
<input type="text" #email="ngModel" [(ngModel)]="userService.selectedUser.email" name="email" placeholder="Email"
required [pattern]="emailRegex" [ngClass]="{'invalid-textbox' :signUpForm.submitted && !email.valid }">
<div *ngIf="signUpForm.submitted && email.errors">
<label *ngIf="email.errors.required" class="validation-message">This field is required.</label>
<label *ngIf="email.errors.pattern" class="validation-message">Invalid email address.</label>
</div>
<input type="password" #password="ngModel" [(ngModel)]="userService.selectedUser.password" name="password" placeholder="Password"
minlength="4" required [ngClass]="{'invalid-textbox' :signUpForm.submitted && !password.valid }">
<div *ngIf="signUpForm.submitted && password.errors">
<label *ngIf="password.errors.required" class="validation-message">This field is required.</label>
<label *ngIf="password.errors.minlength" class="validation-message">Enter atleast 4 characters.</label>
</div>
Error:
Property 'required' comes from an index signature, so it must be accessed with ['required'].
When changed to *ngIf="email.errors.['required']"
it gives the error:
Parser Error: Expected identifier for property access at the end of the expression [email.errors.['required']] finally when changed to
*ngIf="[email.errors.['required']]"
it gives the error: Parser Error: Expected identifier for property access at the end of the expression [[email.errors.['required']]]
What am i doing wrong with the validation
Solution
Use:
*ngIf="email.errors?.['required']"
Reference:
Validating input in template-driven forms
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.