Template Driven Form Validation In Angular

Template Driven Form Validation In Angular

In this article, We will learn how to validate forms using templates in Angular. When filling out a web form, it is highly typical for people to make mistakes. The validations are used at this point. The validation module must check that the user has filled out the form fields correctly and completely. We need to show the users the validation error messages and disable the submit button till the validation is complete. In this tutorial, we'll learn how to use the Angular built-in validators and how to manage validations in Template-driven forms in Angular.

Template-driven Form Validation

Validation directives are used to provide validation in Template-driven forms. There are various built-in validators in the Angular Forms Module. You can also make your own Validator from scratch.

Template

Consider the template-driven form below. It has form fields for firstname, lastname, email, gender, and isToc.

Add the following code under the app.componennt.html file.

<form contactform="" ngsubmit="" onsubmit="">
 
  <p>
    <label>First Name </label>
    <input contact.firstname="" id="firstname" name="firstname" ngmodel="" type="text" />
  </p>
 
  <p>
    <label>Last Name </label>
    <input contact.lastname="" id="lastname" name="lastname" ngmodel="" type="text" />
  </p>
 
  <p>
    <label>email </label>
    <input contact.email="" id="email" name="email" ngmodel="" type="text" />
  </p>
 
  <p>
    <label>Geneder </label>
    <input contact.gender="" id="gender" name="gender" ngmodel="" type="radio" value="male" /> Male
    <input contact.gender="" id="gender" name="gender" ngmodel="" type="radio" value="female" /> Female
  </p>
 
  <p>
    <label>Accept TOC</label>
    <input contact.istoc="" id="isToc" name="isToc" ngmodel="" type="checkbox" />
  </p>
 
  <p>
    <button type="submit">Submit</button>
  </p>
 
</form>

Add the following code under the app.componennt.ts file.

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit  {
  title = 'Template driven forms';
 
  @ViewChild('contactForm',null) contactForm: NgForm;
 
  contact:contact;
 
  ngOnInit() {
 
    this.contact = { 
      firstname:"",
      lastname:"",
      gender:"male",
      isToc:true,
      email:"",
    };
 
  }
 
  onSubmit() {
    console.log(this.contactForm.value);
  }
 
}
 
export class contact {
  firstname:string;
  lastname:string;
  gender:string;
  isToc:boolean;
  email:string;
}

Disabling the Browser validation

We must first prevent the browser validator from interfering with the Angular validator. To accomplish this, we must add the novalidate attribute to the <form> element, as seen below.

<form contactform="" ngsubmit="" novalidate="" onsubmit="">

Built-in Validators

The HTML5 validation elements required, minlength, maxlength, and pattern are used by the built-in validators. These validation attributes are interpreted by Angular, and validator functions are added to the FormControl object.

Adding in Built-in Validators

Required Validation

Only if the form control has a non-empty value entered does the needed validator return true. Allow us to include this validator in all fields.

<input contact.firstname="" id="firstname" name="firstname" ngmodel="" required="" type="text" />

Minlength Validation

This Validator demands that the control value be at least as long as the value supplied in the validator.

The minlength validator, for example, verifies that the firstname value has at least 10 characters.

<input contact.firstname="" id="firstname" minlength="10" name="firstname" ngmodel="" required="" type="text" />

Maxlength Validation

The amount of characters must not exceed the attribute's value, according to this Validator.

<input contact.lastname="" id="lastname" maxlength="15" name="lastname" ngmodel="" required="" type="text" />

Pattern Validation

The control value must match the regex pattern specified in the property for this Validator to work. The pattern ^[a-zA-Z]+$, for example, ensures that only letters are allowed (even spaces are not allowed). Let's put this pattern to work on the lastName.

<input contact.lastname="" id="lastname" maxlength="15" name="lastname" ngmodel="" pattern="^[a-zA-Z]+$" required="" type="text" />

Email Validation

The control value for this Validator must be a genuine email address. This is what we do with the email field.

<input contact.email="" email="" id="email" name="email" ngmodel="" required="" type="text" />

Disable Submit button

The validators have now been successfully inserted. The form is still submitted when you click the submit button.

If our form is invalid, we must disable the submit button.

The Angular forms module keeps track of our form's state and each of its form elements. FormGroup, FormArray, and FormControl objects disclose these states to the user.

We create a template variable and bind it to ngForm to retrieve the reference to the top-level FormGroup instance. We already did this when we inserted the #contactForm="ngForm" attribute to our form tag.

The valid property of the FormGroup is set to true if all of its child controls are legitimate. It is used to set the submit's disabled attribute.

<button contactform.valid="" disabled="" type="submit">Submit</button>

The submit button is blocked as long as contactForm.valid is false.

Displaying the Validation/Error messages

We must give the user with a concise and meaningful error message.

For each field, Angular constructs a FormControl with the ngModel directive applied. The FormControl displays the condition of a form element, such as whether it is valid, filthy, or touched.

You can retrieve the reference to the FormControl in one of two methods.

The contactForm variable is one option. To check if the firstname is legitimate, we can use the contactForm.controls.firstname.valid method.

Another option is to make a separate local variable for each FormControl. Firstname="ngModel" generates the firstname variable with the FormControl instance, for example.

<input contact.firstname="" firstname="ngModel" id="firstname" minlength="10" name="firstname" ngmodel="" required="" type="text" />

We can now verify the status of the firstname FormControl object because we have a reference to it. To see if the firstname has any mistakes, we use the valid property.

valid: returns either an invalid status or null, indicating that the status is valid.

<div ngif="!firstname?.valid &amp;&amp; (firstname?.dirty || firstname?.touched)">
   Invalid First Name
</div>

Why check dirty and touched?

We don't want the application to show the error the first time the form is presented. Only after the user has attempted to change the value should errors be displayed. The dirty and touched properties help us to do that.

dirty: A control is dirty if the value in the UI has been updated by the user.
touched: If the user has initiated a blur event on a control, it is considered touched.

Error message

"Invalid First Name" is not a helpful error message. There are two validators for the firstname. minlength and required

The errors object is updated with any errors generated by the unsuccessful validation. The errors object returns either the error object or null if no errors exist.

<div ngif="!firstname?.valid &amp;&amp; (firstname?.dirty || firstname?.touched)">
  Invalid First Name
  <div ngif="firstname.errors.required">
     First Name is required
  </div>
  <div ngif="firstname.errors.minlength">
    First Name Minimum Length is {{firstname.errors.minlength?.requiredLength}}
  </div>
</div>

The minlength validators return firstname.errors.minlength?.requiredLength, which is what we use to display the error message.

The following code is complete code of the app.componennt.html page. 

<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" novalidate>
  <p>
    <label>First Name </label>
    <input contact.firstname="" firstname="ngModel" id="firstname" minlength="10" name="firstname" ngmodel="" required="" type="text" />
  </p>
  <div class="error" ngif="!firstname?.valid &amp;&amp; (firstname?.dirty || firstname?.touched)">
    <div ngif="firstname.errors.required">
      First Name is required
    </div>
    <div ngif="firstname.errors.minlength">
      First Name Minimum Length is {{firstname.errors.minlength?.requiredLength}}
    </div>
  </div>
 
  <p>
    <label>Last Name </label>
    <input contact.lastname="" id="lastname" lastname="ngModel" maxlength="15" name="lastname" ngmodel="" pattern="^[a-zA-Z]+$" required="" type="text" />
  </p>
  <div class="error" ngif="!lastname?.valid &amp;&amp; (lastname?.dirty || lastname?.touched)">
    <div ngif="lastname.errors.required">
      Last Name is required
    </div>
    <div ngif="lastname.errors.maxlength">
      Last Name Minimum Length is {{lastname.errors.maxlength?.requiredLength}}
    </div>
    <div ngif="lastname.errors.pattern">
      Only characters are allowed
    </div>
  </div>
 
 
 
  <p>
    <label>email </label>
    <input contact.email="" email="ngModel" id="email" name="email" ngmodel="" required="" type="text" />
  </p>
  <div class="error" ngif="!email?.valid &amp;&amp; (email?.dirty || email?.touched)">
    <div ngif="email.errors.required">
      Email is required
    </div>
    <div ngif="email.errors.email">
      Invalid Email Address
    </div>
  </div>
 
  <p>
    <label>Geneder </label>
    <input contact.gender="" gender="ngModel" id="gender" name="gender" ngmodel="" required="" type="radio" value="male" />
    Male
    <input contact.gender="" gender="ngModel" id="gender" name="gender" ngmodel="" required="" type="radio" value="female" /> Female
  </p>
  <div class="error" ngif="!gender?.valid &amp;&amp; (gender?.dirty || gender?.touched)">
    <div ngif="gender.errors.required">
      Gender is required
    </div>
  </div>
 
 
  <p>
    <label>Accept TOC</label>
    <input contact.istoc="" id="isToc" istoc="ngModel" name="isToc" ngmodel="" required="" type="checkbox" />
  </p>
  <div class="error" ngif="!isToc?.valid &amp;&amp; (isToc?.dirty || isToc?.touched)">
    <div ngif="isToc.errors.required">
      Please accept the TOC
    </div>
  </div>
 
  <p>
    <button contactform.valid="" disabled="" type="submit">Submit</button>
  </p>
 
  <p>{{contactForm.valid}} </p>
 
</form>


Conclusion

Validators are directives used in Angular template-driven form validation. Validators are responsible for handling form validations and displaying validation messages. For this purpose, Angular provides various built-in validators. Minlength, maxlength, email, pattern, needed, and so on are some of them.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post