Angular 2 Custom Directive – Form Validation

2
201

Introduction:
Form field validations are very important  to restrict from user to enter invalid data on client side. In this post explained simple example to validate form input fields using custom directive. And also explained, injection of bootstrap library to the template for form styling.

Create a  form template  file and  avoid default HTML 5 validations by  adding form property novalidate.

forms.component.html :

Create a component with component selector name is “form-component” and add templateUrl path.

form.component.ts:

Now in order to add styles to your component, define stylesUrl path to your component meta data like below.

Updated form.component.ts:

Note: You should install bootstrap css library using npm install (by adding “bootstrap”:”~3.3.7″ to the devDependencies property in package.json file). Then add above mentioned path.

Create a directive with selector name “validateValue”, we can use this directive, by simply injecting directive selector name to the form template.

Now update our form template by adding  directive selector name as attribute to  the our form fields like below.

Updated forms.component.html :

In the above code,we are passing field values (like [validateValue]="uname" ) and field name (like fieldName="name" ) to the directive. Now update our directive file by adding input properties.

validation.directive.ts:

Add a constructor function to get the template DOM control to the directive and also add HostListener to listen the input field events.

Updated validation.directive.ts:

Now you are getting model data and elements to the directive, so you can write your validations. Refer below input field validation code.

Updated validation.directive.ts:

 

source code :  link

 

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here