Home > OS >  Angular validation error: Property Required, and Parser Error
Angular validation error: Property Required, and Parser Error

Time:02-26

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" >This field is required.</label>
    <label *ngIf="email.errors.pattern" >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" >This field is required.</label>
    <label *ngIf="password.errors.minlength" >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

CodePudding user response:

Use:

*ngIf="email.errors?.['required']"

Reference:

Validating input in template-driven forms

  • Related