Blog

  • Validation in Angular?

    Angular ships with a number of in-built Validators such as required, email validators etc. which can be used to provide a very nice frontend for our app and can be used to create powerful forms. However, we can also build our own custom Validators depending upon our requirement while using the Reactive approach of handling forms in Angular. Let’s take an example of a simple form which is having a username and an email field as given below:-

     

    app.component.html :-

    <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
        <label for="username">Username</label> 
        <input formControlName="username" id="username" type="text" /> 
    
    
        <label for="email">Email</label> 
        <input formControlName="email" id="email" type="text" />
    
    
        <button type="submit">Submit</button>
    </form>
    

    Creating our Custom Validator

    Now we can obviously use the in-built Validators in Angular to check whether the field is empty and also to check the validity of the email field. Let’s suppose we have some user names that we don’t want to allow the user to use. For this we will add a property i.e. forbiddenUsernames in our typescript file which will be an array containing the names we don’t want the user to use. Now we want to create a Validator which checks whether the username entered by the user is one of the two names stored in this property. A Validator is just a function which gets executed whenever Angular checks the validity of its Controls. So let us create a function (or we can say a Validator) named as forbiddenNames(). We should keep following things in mind while creating a Validator:-

    • A Validator, to work correctly needs to receive an argument which is the control it should check and it will be of type FormControl.
    • A Validator also needs to return something for Angular to be able to handle the returned value correctly. This something should be a javascript object and this object should have any key which can be interpreted as a string and more importantly the value of the key should be a boolean.

    Now, we can add the logic inside our function( or Validator) which in our case we want to check whether the value of the control is one of the two names specified in our forbiddenUsernames property. We should keep one thing in mind that if the validation is successful we have to pass nothing or null, we should not pass the object as false as it won’t work. We have to pass null or we can simply emit the return statement. Now we can use our custom Validator by adding it to the array of validators in our typescript file.

    app.component.ts file:-

    import { Component , OnInit } from '@angular/core';
    import { FormGroup , FormControl , Validators} from '@angular/forms';
    @Component({ selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
        signupForm : FormGroup;
        forbidden = ['Anna' , 'Chris'];
        ngOnInit(){
          this.signupForm = new FormGroup({
            'username' : new FormControl(null , [Validators.required , this.forbiddenNames.bind(this)]),
            'email' : new FormControl(null , [Validators.required , Validators.email])
          })
        }
        onSubmit(){
            console.log(this.signupForm);
        }
        //custom validator
        forbiddenNames(control : FormControl): {[s: string]: boolean}{
            if(this.forbidden.indexOf(control.value) !== -1)
                { return{'nameIsForbidden' : true}
            }
            return null;
        }
    }

     

Tags: AngularJS