I am using FormGroup, FormBuilder and Validators class to validate a form in Angular2 app.
This is how I am defining the required validation rules for email and password validation:-
export class LoginComponent implements OnInit {
loginFormGroup:FormGroup;
adminLoginmodel = new Admin('', '', '', 'Emailsss','Passwordsss');
constructor(
private route: ActivatedRoute,
private router: Router,
private _adminLogin: AdminLoginService,
fb: FormBuilder
){
this.loginFormGroup = fb.group({
'email' : [null, Validators.compose([Validators.required, Validators.email])],
'password': [null, Validators.required]
});
}
}
The code Validators.compose([Validators.required, Validators.email])
checks both whether an email field is empty and whether the provided string is valid email.
However, I don't know how to show different validation message in different cases. Say
- If email field is empty, I need to display "Please provide an email address"
- If provided email is not valid, then I need to display "Provided email is not a valid email".
Here is how I was displaying validation message in my html:-
<div class="input-group input-group-lg" [ngClass]="{'has-error':!loginFormGroup.controls['email'].valid && loginFormGroup.controls['email'].touched}">
<span class="input-group-addon"><i class="glyphicon glyphicon-user red"></i></span>
<input type="text" class="form-control" placeholder="Email" id="email" name="email" [formControl]="loginFormGroup.controls['email']" [(ngModel)]="adminLoginmodel.email"/>
</div>
<div class="alert alert-danger" *ngIf="!loginFormGroup.controls['email'].valid">You must add an email.</div>
How can I show different messages in different cases?
Live demo
Discussion in the comments proved that the answer to this specific problem is: