0
votes

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]
         });
    }
}

This is my html script:-

<form class="form-horizontal" role="form" [formGroup]="loginFormGroup" (ngSubmit)="submitPost(loginFormGroup.value)" method="post">
<fieldset>
    <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'].hasError('email')">Provide a valid email.</div>
    <div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">You must add an email.</div>

    <div class="clearfix"></div><br>
    <div class="input-group input-group-lg" [ngClass]="{'has-error':!loginFormGroup.controls['password'].valid && loginFormGroup.controls['password'].touched}">
        <span class="input-group-addon"><i class="glyphicon glyphicon-lock red"></i></span>
        <input type="password" class="form-control" placeholder="Password" id="password" name="password" [formControl]="loginFormGroup.controls['password']" [(ngModel)]="adminLoginmodel.password"/>
    </div>
    <div class="alert alert-danger" *ngIf="!loginFormGroup.controls['password'].valid">You must add a password.</div>
    <div class="clearfix"></div>
    <p class="center col-md-5">
        <button type="submit" class="btn btn-primary" [disabled]="!loginFormGroup.valid">Login</button>
    </p>
    <div class="clearfix"></div>
</fieldset>
</form>

Question 1: How to show only one validation message when two validation messages are showing up for a single input field?

Check this image given below:-

Two message

When no data is present inside the email field, both the validation rules are satisfying:-

  1. The field has no data, so data is required.
  2. The empty data is not a valid email, so valid email is required.

Instead of two validation messages, I need to show only one validation message. If email is not given, then it should display "You must add an email". When email is given and it is not a valid email, then only it will display "Please provide a valid email" How can I achieve this?

Question 2: How to show validation message only when the user interacts with the form?

Currently, the validation messages are loading up even when the page is loading up for the first time. Even when the user is not entering any value in the field or clicking the button, still the validation message is showing up. The validation message should only show up when user does any action on the form. How can I achieve this?

1
It would be better to split this into two separate quesitons.Tomasz Kula

1 Answers

1
votes

First question

<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('email') && !loginFormGroup.controls['email'].hasError('required')">Provide a valid email.</div>
<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">You must add an email.</div>

Second question: Control Status Classes

Angular automatically mirrors many control properties onto the form control element as CSS classes.

  • .ng-valid
  • .ng-invalid
  • .ng-pending
  • .ng-pristine
  • .ng-dirty
  • .ng-untouched
  • .ng-touched

So in your case you need to check if your control is dirty, before checking it it's invalid.

<ng-container *ngIf="loginFormGroup.controls['email'].dirty">
  <div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('email')">Provide a valid email.</div>
  <div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">You must add an email.</div>
</ng-container>