Validators 클래스
폼콘트롤에서 사용할 수 있는 내장 유효성검사함수를 제공한다.
class Validators {
static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
static required(control: AbstractControl): ValidationErrors | null
static requiredTrue(control: AbstractControl): ValidationErrors | null
static email(control: AbstractControl): ValidationErrors | null
static minLength(minLength: number): ValidatorFn
static maxLength(maxLength: number): ValidatorFn
static pattern(pattern: string | RegExp): ValidatorFn
static nullValidator(control: AbstractControl): ValidationErrors | null
static compose(validators: ValidatorFn[]): ValidatorFn | null
static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
}
static으로 함수가 선언되어있으며 ValidatorFn를 반환하거나 ValidationErrors | null을 반환한다.
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}
ValidatorFn은 ValidationErrors | null을 반환한다.
유효성검사함수가 ValidatorFn를 반환하면 앵귤러가 폼콘트롤을 인자로해서 호출하도록 되어있다.
ngOnInit() {
const regExp = /admin/i;
this.heroForm = new FormGroup({
nameFC:new FormControl(this.hero.name,[
Validators.required, Validators.minLength(4), forbiddenNameValidator(regExp)
]),
alterEgoFC:new FormControl(this.hero.alterEgo),
power:new FormControl(this.powers[0])
});
}
export function forbiddenNameValidator(regExp:RegExp):ValidatorFn{
return (control:AbstractControl):ValidationErrors|null=>{
const ret = regExp.test(control.value);
return ret?{forbiddenName:control.value}:null;
}
}
커스텀 유효성검사함수도 ValidatorFn함수를 반환하도록 정의하고 설정하면 앵귤러가 폼콘트롤을 인자로해서 호출하여 ValidationErrors|null를 반환받기때문에 유효성검사가 이루어진다.