I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the log
Here is an example that works:
MatchPassword(AC: FormControl) {
let dataForm = AC.parent;
if(!dataForm) return null;
var newPasswordRepeat = dataForm.get('newPasswordRepeat');
let password = dataForm.get('newPassword').value;
let confirmPassword = newPasswordRepeat.value;
if(password != confirmPassword) {
/* for newPasswordRepeat from current field "newPassword" */
dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
if( newPasswordRepeat == AC ) {
/* for current field "newPasswordRepeat" */
return {newPasswordRepeat: {MatchPassword: true} };
}
} else {
dataForm.controls["newPasswordRepeat"].setErrors( null );
}
return null;
}
createForm() {
this.dataForm = this.fb.group({
password: [ "", Validators.required ],
newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]
});
}
Though its late but following solution worked form me.
let control = this.registerForm.controls['controlName'];
control.setErrors({backend: {someProp: "Invalid Data"}});
let message = control.errors['backend'].someProp;
For unit test:
spyOn(component.form, 'valid').and.returnValue(true);
Adding to Julia Passynkova's answer
To set validation error in component:
formData.form.controls['email'].setErrors({'incorrect': true});
To unset validation error in component:
formData.form.controls['email'].setErrors(null);
Be careful with unsetting the errors using null
as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:
if (isIncorrectOnlyError){
formData.form.controls['email'].setErrors(null);
}
You could also change the viewChild 'type' to NgForm as in:
@ViewChild('loginForm') loginForm: NgForm;
And then reference your controls in the same way @Julia mentioned:
private login(formData: any): void {
this.authService.login(formData).subscribe(res => {
alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
}, error => {
this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
this.loginForm.controls['email'].setErrors({ 'incorrect': true});
this.loginForm.controls['password'].setErrors({ 'incorrect': true});
});
}
Setting the Errors to null will clear out the errors on the UI:
this.loginForm.controls['email'].setErrors(null);
In new version of material 2 which its control name starts with mat prefix setErrors() doesn't work, instead Juila's answer can be changed to:
formData.form.controls['email'].markAsTouched();