angular 5 form validation easiest way

angular 5 form validation example angular 5 custom validator angular 5 custom validators angular 5 email validation pattern angular 5 validators angular 5 custom validator example angular 5 formbuilder validation angular 5 formgourp validation angular 5 simplest validation

Angular make form validation easier than ever, we are going to check with Angular FormBuilder, FormGroup and validation together in this article, We will also see how to validate email without writing any custom directive or any other code because it is already there. Some tricky way to show and hide the error on page load and on save. We will use plunker for example:

First we need to update our app.module.ts:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
  .....
}) 

What is ReactiveFormsModule, FormGroup, FormBuilder etc, please see https://angular.io/guide/reactive-forms

In this article we are going to use FormBuilder and FormGroup to generate our form and validation, so import following

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

export class AppComponent implements OnInit{ 
    register: FormGroup;        

    constructor(private frmBuilder: FormBuilder) { }

    ngOnInit(){
     this.register = this.frmBuilder.group({
       name:["", [Validators.required, Validators.minLength(3),Validators.maxLength(15)]],
       email:["", [Validators.required]],
       password:["", [Validators.required]],
       verify:["", [Validators.required]]

     });
    }
}

Let's see them line by line:

  • register: FormGroup; created an object of FromGroup
  • frmBuilder: an object of FromBuilder in our constructor
  • then we created a group of properties and validations in our OnInit function

email:["", [Validators.required]]

  • email: is the property name
  • "": default value (we can also use null)
  • [Validators.required]: an array of validations, it can be any number of validations, see the name validation

What is FormGroup

Let's say we have to create structure like person information which have information in groups like this:

person:{
    name: string,
    age: number,
    address: {
        city:string,
        state:string,
        zipcode: string
    },
    contact: {
        phone: string,
        fax: string,
        email: string
    }
}

To create this structure with FormBuilder and Form Group we can create this structure easily, see this:

personForm: FormGroup;

this.personForm = this.frmBuilder.group({
    name: [null, [Validators.required]],
    age: '',
    address: this.frmBuilder.group({
        city: [null, [Validators.required]],
        state: ['NY'],
        zipcode: ''         
    }),
    contact: this.frmBuilder.group({
        phone: ''.
        fax:'',
        email: ['', [Validators.required]]
    })
});

Let's go back to our register form and add HTML for it, we need to add a form tag and tell this form tag about our form group name:

<form [formGroup]='register' (ngSubmit) = 'save()' novalidate>
    <input type='text' 
           formControlName='name'
           class='form-control'
           placeholder='Enter Display Name'>
</form>

Note the formControlName, it bind the control with our defined details in our form group. (ngSubmit)='save()', since our save button type is submit, when user will click on it, it will call the save method on our component, which we will defile latter.

Here is the complete form HTML code without any validation code:

<form [formGroup]='register'  (ngSubmit) = 'save()' novalidate>
    <div class='row'>
      <div class='col-sm-6'>
        <input type='text' formControlName='name'
               class='form-control'
               placeholder='Display Name'>
      </div>
    </div>

    <div class='row'>
      <div class='col-sm-6'>
        <input type='text' formControlName='email'
               class='form-control'
               placeholder='Email'>
      </div>
    </div>

    <div class='row'>
      <div class='col-sm-6'>
        <input type='text' formControlName='password'
               class='form-control'
               placeholder='Password'>
      </div>
    </div>


    <div class='row'>
      <div class='col-sm-6'>
        <input type='text' formControlName='verify'
               class='form-control'
               placeholder='Verify Password'>
      </div>
    </div>

    <div class='row'>
      <div class='col-sm-6'>
        <button type='submit' class='btn btn-primary'>Save</button>
        <button type='submit' class='btn btn-warning'>Cance</button>
      </div>
    </div>
</form> 

Before adding the validation messages, we need to know, how to get the error detail of any control, Angular team suggest to use the property to get the detail of any control like this:

get name() { return this.register.get('name'); } get email() { return this.register.get('email'); } get password() { return this.register.get('password'); } get verify() { return this.register.get('verify'); }

Now we can use these getters to get the detail and add the errors only be one

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.maxlength">
    Name must not exceed 15 characters.
  </div>
</div>

What this code means:

  • First ngIf: name is invalid, dirty or touched only then show the message
  • Rest are checking for special type of error and show different messages

I am not happy with dirty or touched, when user will click the Save button it will not show any error, rather I want to show the message when user change any value or try to submit the page, show all the invalid fields, for that we need to add a boolean variable in our component saying `isSubmitted', default to false and make it true on clicking the save button

isSubmitted: boolean = false;

save(){
   this.isSubmitted = true;
   if(!this.register.valid)
      return;
   // Code to save the data
   // userService.Save(this.register.value);
}

Now change our validations error showing message to this:

<div *ngIf="name.invalid && (name.dirty || isSubmitted)" class="text-danger">
  .........
  .........
</div>

Let's add the code to show the error message for different controls with different conditions:

Name Error have three things, required, min-length and max-length:

<div *ngIf="name.invalid && (name.dirty || isSubmitted)" class="text-danger">
  <div *ngIf="name.errors.required">
    Name is required.
  </div>
  <div *ngIf="name.errors.minlength">
    Name must be at least 4 characters long.
  </div>
  <div *ngIf="name.errors.maxlength">
    Name must not exceed 15 characters.
  </div>
</div>

Email, password and verify password: for now it is only required so we can use the simplest one

<div *ngIf="email.invalid && (email.dirty || isSubmitted)" class="text-danger">
    Email is required.
</div>    
<div *ngIf="password.invalid && (password.dirty || isSubmitted)" class="text-danger">
    Password is required.
</div>     
<div *ngIf="verify.invalid && (verify.dirty || isSubmitted == true)" class="text-danger">
    Verify Password is required.
</div>

Now when any control value changed and not valid or user try to save and values are not valid then we can show the errors

Here is the save function which test the value before sending to the service to save into database:

save(){
    this.isSubmitted = true;
    if(!this.register.valid)
     return;
    // Code to save the data
    // userService.Save(this.register.value);
    this.result = this.register.value;
    setTimeout(()=> {
        this.result = null;
                    this.reset();
    }, 2000);
}
  • First it make the for isSubmitted to true
  • then check if form is valid or not, if not valid return to the page
  • if valid just put the code in a variable to show on the page, code to call service will go here
  • finally we remove the result from variable in 2 seconds and call the reset

Reset Controls

If we save the data and stay on the same page, might be the case, then we need to reset our form to accept the new record, not in the case of registration. So how to reset the controls and this is the simplest step just call reset on our form, see this

reset(){
    this.isSubmitted = false;
    this.register.reset();   
}

Here two things are missing, email validation and verify password comparison which we will see in our next article.

Go ahead and see: Angular 5 email & compare password validation, different ways

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • angular-5
  • angularjs
  • validation
  • FormGroup
  • ReactiveForm
By Ali Adravi On 23 Jan, 18  Viewed: 3,727

Other blogs you may like

Angular 5 email & compare password validation, different ways

Angular email validation can be done in many different ways, by using the built-in directive, by using patterns or by creating custom directive. In this article we will try to see all the three different ways with working code in plunker. We will use our previous example and add three email text... By Ali Adravi   On 23 Jan 2018  Viewed: 16,954

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 19,721

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 4,497

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 31,463

Angularjs Progress bar directive for entire application

Progress bar for Angularjs application by using directives is simple and real easy. I was googling and could not found any directive way, if you will check most of the people says before call the http method open the progress bas and close once you get the result or get any error. Do you think it... By Ali Adravi   On 24 Jul 2015  Viewed: 14,201