Angular 5 Forms And Validations - Part One

Forms are the main building blocks of any application. When we use forms for login, registration, submission, help request, etc., it is necessary that whatever form we are developing, they must be user-friendly. And, it should have the indication of what went wrong etc.

Coming to the Angular Forms, Angular provides 2 approaches for developing forms - Template Driven and Reactive forms. Let’s try to explore the template-driven approach in this article.

Template Driven Forms

Template driven forms are simple forms which can be used to develop forms. These are called template-driven as everything that we are going to use in a application is defined into the template that we are defining along with the component. Let’s see step by step how we can develop and use these forms in the application.

Prerequisite

We need to import FormsModule in an Application module file (i.e.app. module.ts).

@angular/Forms

The code snippet for that can be like this.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import {FormsModule} from '@angular/forms'  
  4. import { AppComponent } from './app.component';  
  5. @NgModule({  
  6.   declarations: [  
  7.     AppComponent,  
  8.       
  9.   ],  
  10.   imports: [  
  11.     BrowserModule,  
  12.     FormsModule  
  13.   ],  
  14.   providers: [],  
  15.   bootstrap: [AppComponent]  
  16. })  
  17. export class AppModule { }  

Alright!  This is the basic import that we need to do before we are ready to use these forms in our application so as to pass data from  HTML to the component.

Let's have the code snippet of the form which we will be using here.

  1. <div class="container">  
  2.   <div class="row">  
  3.       <div class="form_bg">  
  4.           <form #regForm='ngForm' (ngSubmit)="Register(regForm)" >  
  5.                <h2 class="text-center">Registration page</h2>  
  6.               <br/>  
  7.               <div class="form-group">  
  8.                   <input type="text" class="form-control" placeholder="First Name" name="firstname" ngModel >   
  9.               </div>  
  10.               <div class="form-group">  
  11.                   <input type="text" class="form-control"  placeholder="Last Name" name="lastname" ngModel >  
  12.               </div>  
  13.               <div class="form-group">  
  14.                   <input type="email" class="form-control" id="email" placeholder="Email" name="email" ngModel>  
  15.                     
  16.               </div>  
  17.                <div class="form-group">  
  18.               </div>  
  19.               <br/>  
  20.               <div class="align-center">  
  21.                   <button type="submit" class="btn btn-default" id="register"  >Register</button>  
  22.               </div>  
  23.           </form>  
  24.       </div>  
  25.   </div>  
  26. </div>  

Above code has some elements - first name, last name, email, and a submit button. Now that our form is ready, we need to pass these value to component.

First step in using the forms is understanding the ngForm and the ngModel directives that we used above.

NgForm

It is the directive which helps to create the control groups inside form directive. It is attached to the <form> element in HTML and supplements form tag with some additional features. Some interesting things we can say about View are that whenever we use the directive in the application view, we need to assign some selector with it and the form is the said selector in our case. The next thing that we need to consider is the ngModel attribute that we have assigned to each HTML control. Let’s see what this attribute does.

NgModel

When we add NgModel Directive to the control, all the inputs are registered in the NgForm.

It creates the instance of the FormControl class from Domain model and assigns it to the form control element. This control keeps track of the user information and the state and validation status of the form control.

Next important thing to consider is that when we use NgModel with the form tag or most importantly, with the NgForm, we make use of the name property of HTML control. When we look at the above snippet, every control is assigned a name property and we have added the ngModel attribute to the control.

e.g.

<input type="email" class="form-control" id="email" placeholder="Email" name="email" ngModel>

Two main functionalities offered by NgForm and NgModel are the permission to retrieving all the values of the control associated with the form and then retrieving the overall state of controls in the form.

To expose ngForm in the application, we have used the following code snippet.

  1. <form #regForm='ngForm' (ngSubmit)="Register(regForm)" >  

In this, we are exporting the ngForm value in the local variable “regform”. Now, the question arises, whether or not we need to use this local variable. Well, the answer is no. We are exporting ngForm in the local variable just to use some of the properties of the form and these properties are -

  1. regForm.Value: It gives the object containing all the values of the field in the form.
  2. regForm.Valid: This gives us the value indicating if the form is valid or not if it is valid value is true else value is false.
  3. regForm.touched: It returns true or false when one of the field in the form is entered and touched.
  4. regForm.submitted: It checks whether the form is submitted or not. It returns true and false value.

In the above case, we have noticed that the Form Tag has no action method or attribute specified there, so how so we post the data in the component?

Let’s have a look at the (ngSubmit)=”Register(regForm)”. Here, we are using the Event Binding concept and we are binding which will call the Register method in the component. Instead of the submit event of the form, we are using ngSubmit which will send the actual HTTP request instead of just submitting the form.

Now, when we look at the component, we can see that.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { NgForm } from '@angular/forms';  
  3. @Component({  
  4.   selector: 'app-formdemobasics',  
  5.   templateUrl: './formdemobasics.component.html',  
  6.   styleUrls: ['./formdemobasics.component.css']  
  7. })  
  8. export class FormdemobasicsComponent implements OnInit {  
  9.   
  10.   constructor() { }  
  11.   
  12.   ngOnInit() {  
  13.   }  
  14.   
  15.   Register(regForm:NgForm){  
  16.     console.log(regForm);  
  17.       
  18.   }  
  19. }  

Here, we have the Register method in the component. It accepts the ngForm object and it has all the values from the template to display in the console.

Note

In combination with the name attribute, ngModel creates the abstraction over the form state and it automatically shows up in the forms value collection (i.e.form.value).

Validations

Validation is an important aspect of programming. We cannot trust the user that’s why we always want to validate the data. So, to prevent the user from entering wrong data and show some proper value, we check and ask the users to add the proper data.

How do we validate the template driven forms then?

The answer is - by using the Angular set of common validators like minlength,maxlength, required, email. We just need to add the validator directive to the control for assigning the controls the validators.

Let's see the template of the new sign up form that we have added. The code snippet for the same is as follows.

  1. <div class="container">  
  2.     <div class="row">  
  3.         <div class="form_bg">  
  4.             <form #form="ngForm" (ngSubmit)="registerUser(form)">  
  5.                  <h2 class="text-center">Registration page</h2>  
  6.                 <br/>  
  7.                 <div class="form-group">  
  8.                     <input type="text" class="form-control" placeholder="First Name" name="firstname" required ngModel>   
  9.                 </div>  
  10.                 <div class="form-group">  
  11.                     <input type="text" class="form-control"  placeholder="Last Name" name="lastname" required ngModel>  
  12.                 </div>  
  13.                 <div class="form-group">  
  14.                     <input type="email" class="form-control" id="email" placeholder="Email" name="email" email required ngModel #email="ngModel">  
  15.                     <span class="help-bpx" *ngIf="email.touched && !email.valid ">Please enter the Email Value</span>  
  16.                 </div>  
  17.                  <div class="form-group">  
  18.                 </div>  
  19.                 <br/>  
  20.                 <div class="align-center">  
  21.                     <button type="submit" class="btn btn-default" id="register" [disabled]="!form.valid" >Register</button>  
  22.                 </div>  
  23.             </form>  
  24.         </div>  
  25.     </div>  
  26. </div>  

Let's see the sample for the basic validation required for the user name.

  1. <input type="text" class="form-control" placeholder="First Name" name="firstname" required ngModel>  

What we need here is that we need to show the Red Border whenever the first name is not entered in the control. Here, we can make use of the Angular CSS classes to achieve that, that will be applied and removed whenever the state of the form changes. The following are the classes which will be attached whenever the state is changed.

  1. ng-touched: Controls have been visited
  2. ng-untouched: controls have not been visited
  3. ng-dirty : control value has been changed
  4. ng-pristine:Controls value have not been changed
  5. ng-valid : control values are valid
  6. ng-invalid : control values are invalid

So, in order to draw a border around the first name whenever a user visits the control and does not add any value, we need to use these classes.

Here is how -

  1. input.ng-invalid.ng-touched  
  2. {  
  3.    border-color: red;  
  4. }  

This is just the CSS logic that is adding the red border around the control and displaying it in the UI. Now, suppose, we have a requirement to show the validation message for the particular control state. Let's see another example for understanding this. Consider the email field.

We need to show the Required as well as to check if the email entered is valid or not. The following code snippet does that for us. 
  1. <input type="email" class="form-control" id="email" placeholder="Email" name="email" email required ngModel #email="ngModel">  
  2. <span class="help-bpx" *ngIf="email.touched && !email.valid ">Please enter the Email Value</span>  

Here, we have used the template reference variable and assigned the ngModel (i.e. state of the control) to that variable. Here, we have a span element which is displayed only when the email is entered but the email is not valid. For that, we have used ngIf in the span element. It is structural directive which will be displayed only if the email entered is invalid.

References

  1. Angular official website (https:\\angular.io)
  2. https:\\rangle.io\