I'm working with Form Controls, which I thought I had a good grasp on. Right now I have a function that creates the controls and assigns their respective Validators.
For this.password1:FormControl and this.password2:FormControl, there should be an errors object like errors:{required: true, pattern:true}. However, the pattern property does not appear in the errors object for either one. I even added in Validators.minLength(8)to the this.password2 FormControl to see if it worked and the minLength error property did not appear either. The flip side is 'this.email' has the right error with errors: {required: true, email: true}.
Note: When I test the validity of the form. It does do the pattern checks and min length checks. I just can't access the errors properties that are supposed to be created. When I console.log the errors property on the FormContril all I get is errors:{required: true}.
Any help would be appreciated as to why the error properties are not created. Happy Thanksgiving!
ngOnInit() {
this.title.setTitle(this.pageTitle);
this.createFormControls();
this.createForm();
}
createFormControls(): void {
const mediumRegex = new RegExp('(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})');
this.email = new FormControl('', Validators.compose([Validators.required, Validators.email]));
this.firstName = new FormControl('', Validators.compose([Validators.required]));
this.lastName = new FormControl('', Validators.compose([Validators.required]));
this.password1 = new FormControl('', Validators.compose([Validators.required, Validators.pattern(mediumRegex)]));
this.password2 = new FormControl('', Validators.compose([Validators.minLength(8), Validators.required, Validators.pattern(mediumRegex)]));
console.log(this.email);
}
matchPassword(AC: AbstractControl): any {
const password1 = AC.get('password1').value; // to get value in input tag
const password2 = AC.get('password2').value; // to get value in input tag
if (password1 !== password2) {
// console.log('false');
AC.get('password2').setErrors({'MatchPassword': true});
// console.log(AC);
// console.log(this.registrationForm);
} else {
// console.log('true');
return null;
}
}
createForm(): void {
this.registrationForm = this.fb.group({
email: this.email,
firstName: this.firstName,
lastName: this.lastName,
password1: this.password1,
password2: this.password2,
}, {
validator: this.matchPassword // your validation method
});
}