Programuse Programuse - 1 month ago 16
TypeScript Question

How do i add more that one Validator argument in Angular 2 form

I have tried adding multiple angular validator arguments [i.e Validators.minLength(8) and Validators.maxLength(12) ] to my form and i cant seem to get it to work...these arguments are attached to the (password and passwordc) instance in the code below. Any help please?

export class signupComponent {
signupform: FormGroup;
constructor(public fb: FormBuilder) {
this.signupform = this.fb.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
account: this.fb.group({
email: ['', Validators.required],
**password: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')],
passwordc: ['', Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')],
}, { validator: passwordMatcher }),**
shortbio: ['', Validators.required]
});

}
}

Answer

To support multiple validators, you have to use the Validators.compose( [ ] ) method that accepts an array of validators. In your case:

password: ['', Validators.compose([Validators.minLength(8), Validators.maxLength(12), Validators.pattern('[A-Za-z]{5}')])]
Comments