Angular Forms - Validators
Angular validators
- required
- requiredTrue
- email
- min
- max
- minLength
- maxLength
- pattern
- nullValidator
How to use
Simply add your validations while constructing the FormControl
this.fb.control('',
[Validators.required, Validators.maxLength(5)])
this.fb.control('',
Validators.required)
Custom validations
function customerNumberValidator(control: FormControl)
: { [s: string]: boolean } {
if (!control.value.match(/^P1000/)) {
return {invalidCustomerNumber: true};
}
}
this.fb.control('', customerNumberValidator)
Custom validations over multiple fields
function distinctValueValidator(formArray: FormArray)
: { [s: string]: boolean } {
const values = formArray.controls
.map(control => control.value);
const uniqueValues = new Set(values);
if (values.length !== uniqueValues.size) {
return {notDistinctValues: true};
}
}
this.fb.array([...], distinctValueValidator)