Search code examples
javascriptangularangular-validation

angular template driven form validation messages


I am using angular template driven form. Currently I show the error messages inside the HTML page.

    <input 
  type="email" 
  name="email" 
  ngModel 
  #email="ngModel" 
  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" 
  required>
<br/>

<div *ngIf="email.touched">
  <p *ngIf="email.errors?.required">Email is a required</p>
  <p *ngIf="email.errors?.pattern">This is not a valid Email!!!</p>
</div>

Example Form

I need to move these error messages to my component file. is there any way to do it ?


Solution

  • I have create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations for the template-driven form.

    We will consider the following custom validations for this demo:

    • Checking for user name availability.

    • Password pattern validation

    • Matching the password entered in two different fields

    Here is the example of Template Driven Form:

    https://stackblitz.com/edit/angular-ivy-eqbltt