Building Custom Validators in Angular 4
Posted By : Satwinder Singh | 09-Apr-2018
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:-
<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
- 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;
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Satwinder Singh
Satwinder had been working as a free-lancer for past 1-year and recently joined Oodles Technologies as a UI-Developer. His skills are : Jquery , Html , Css , Bootstrap and Javascript.