In this article I discuss on how to use Validators class for validation form field.
First we need to import “Validators” Class so we need to write syntax below in component.
import {Validators, FormBuilder, FormGroup ,FormControl} from '@angular/forms';
You can use the Validators in FormControl or collection of controllers that returns error or null. If null that means it satisfy the condition.
- Min Validator
static min(min: number): ValidatorFn
using this Validator we can set controls have a value greater than a number.
var minamount = new FormControl("", Validators.min('20'))
- Max Validator
static max(max: number): ValidatorFn
using this Validator we can set controls have a value less than a number.
var maxamount = new FormControl("", Validators.min('20000'))
- Required Validator
static required(control: AbstractControl): ValidationErrors|null
using this Validator controls to have a non empty value.
var name= new FormControl("", Validators.required)
- Email Validator
static email(control: AbstractControl): ValidationErrors|null
using this Validator controls for validating email address.
var name= new FormControl("", Validators.email)
- minLength Validator
static minLength(minLength: number): ValidatorFn
using this Validator controls for validating minimum length of the value.
var name= new FormControl("", Validators.minLength(4))
- maxLength Validator
static maxLength(maxLength: number): ValidatorFn
using this Validator controls for validating maximum length of the value.
var name= new FormControl("", Validators.maxLength(20))
- pattern Validator
static pattern(pattern: string|RegExp): ValidatorFn
using this Validator controls for validating pattern satisfy the value.
var name= new FormControl("", Validators.pattern('/name/'))
You can use multiple validtor for the control for that we need to pass into the array like below.
var name = new FormControl("", [Validators.minLength(4),Validators.maxLength(20)])
You can use FormGroup in multiple FormControl its looks like in below code.
const form = new FormGroup({
first: new FormControl('', Validators.minLength(2)),
last: new FormControl(''),
email: new FormControl('', Validators.email),
});
You can also include group-level validators as the second arg in the FormGroup.
Example if we need to validate password & confirm password then you can write code display like below.
const register = new FormGroup({
pwd: new FormControl('', Validators.minLength(8)),
pwdConfirm: new FormControl('', Validators.minLength(8)),
}, pwdMatchValidator);
function pwdMatchValidator(frm: FormGroup) {
return frm.get('password').value === frm.get('passwordConfirm').value
? null : {'mismatch': true};
}
Using Validators Class we can easily validate our form fields.
10