Angular form validation example and tutorial

    Mar 10, 2017       by Pankaj Kumar
angular-form-validation.png

In this demo, we will discuss the form validation in angular 2 and its later version. Since we all come across forms to send data to server and its needed to validate input from the user. So that desired value can be submitted from the form. Html also provide basic level of form-validation. Angular also provides is built in form validation. So let's start how form can be validated by angular.

HTML Form with angular validation messages

So let's move ahead and try to understand it step by step, For this demo I have just created a basic app of angular2 by typing ng new form-validation.  Then opened the app.component.html and paste the below code

 

 
<div class="col-md-4 col-md-offset-4" >
<form name="signup_form" (ngSubmit)="fs.form.valid && signup(fs);" #fs="ngForm" novalidate>
<div class="formbox">
<div class="inputbox">
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !fullname.valid }">
<input type="text" class="form-control" name="name" id="name" placeholder="Name" name="fullname" [(ngModel)]="user.fullName" minlength="6" #fullname="ngModel" required pattern="^[A-Za-z ]+$"/>
<div *ngIf="fs.submitted && !fullname.valid" class="help-block">Full Name is required and must be a valid name</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !email.valid }">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" [(ngModel)]="user.email" #email="ngModel" pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required/>
<div *ngIf="fs.submitted && !email.valid" class="help-block">Invalid Email</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="phone_number" id="phone_number" placeholder="Phone No." [(ngModel)]="user.phone" maxlength="12" minlength="10" #phone="ngModel" required/>
<div *ngIf="fs.submitted && !phone.valid" class="help-block">Enter valid phone</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': fs.submitted && !password.valid }">
<input type="password" class="form-control" name="password" id="user_password" placeholder="Password" [(ngModel)]="user.password" #password="ngModel" required/><!--pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$" -->
<div *ngIf="fs.submitted && !password.valid && (password.touched && password.errors?.required)" class="help-block">Password is required and must be atleast six characters long.</div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm_password" id="confirm_password" placeholder="Confirm Password" [(ngModel)]="confirm_password" #confirmPassword="ngModel" required appConfirmEqualValidator='password'/>
<div *ngIf="fs.submitted && (confirmPassword.touched && confirmPassword.errors?.notEqual && !confirmPassword.errors?.required)" class="help-block" >Password Mismatch</div>
</div>
<div class="form-group">
<div class="checkboxrow">
<input type="checkbox" id="test1" name="cb" #cb="ngModel" [(ngModel)]="user.cb" [required]="user.cb==null">
<label for="test1" control-labekl>Agree with terms and conditions</label>
<div *ngIf="fs.submitted && !cb.valid" class="help-block" >Please agree with terms and conditions</div>
</div>
</div>
<div class="form-group">
<span style="text-align: center;color: #a94442">{{errorMsg}}</span>
<span style="text-align: center;color: #28a745">{{sucsMsg}}</span>
<button type="submit" class="btn btn-primary signin">Sign Up <span class="arrowbtn"><span class="fa fa-arrow-right"></span></span></button>
</div>
</div>
<div class="registerrow text-center">Already have an account ? <a href="javascript:void(0)" id="loginshow">Login here !</a></div>
</div>
</form>
</div>
 

 

In the above code we have simply used some form fields like name,email, phone, password, confirm password which are available in normal registration process. So I will explain the validations for the above form.

To display error messages a div element is included for every input element like below.

 

<div *ngIf="fs.submitted && !cb.valid" class="help-block" >Please agree with terms and conditions</div>

 

In the above code *ngIf validates the errors if form-field data is not valid. In the above form we have added required in the fullName, email, phone. And in the eror message check with fullName.valid or email.valid or phone.valid. And for matching password and confirm password a custom directive is created in a file named confirm-equal-validator.directive.ts. See the code inside this file.

 

 

 
import { Validator,NG_VALIDATORS, AbstractControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';
 
@Directive({
selector:'[appConfirmEqualValidator]',
providers: [{
provide: NG_VALIDATORS,
useExisting: ConfirmEqualValidatorDirective,
multi: true
}]
})
 
export class ConfirmEqualValidatorDirective implements Validator {
@Input() appConfirmEqualValidator: string;
 
validate(control: AbstractControl):{[key:string]: any} |null {
const controlToCompare = control.parent.get(this.appConfirmEqualValidator);
if(controlToCompare && controlToCompare.value !==control.value){
return { 'notEqual': true}
}
return null;
}
}
 

 

Paste the below code inside app.module.ts

import { ConfirmEqualValidatorDirective } from './confirm-equal-validator.directive';

Angular 2 Validation Classes

Angular 2 automatically attached CSS classes to the input elements depending on the state of the control. The following class names are used:

  • ng-touched: Control has been visited
  • ng-untouched: Control has not been visited
  • ng-dirty: Control's value has been changed
  • ng-pristine: Control's value hasn't been changed
  • ng-valid: Control's value is valid
  • ng-invalid: Control's value isn't valid

This way we can empliment  form validation in angular.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends. 

Thanks!!


WHAT'S NEW

Find other similar Articles here: