Thursday, November 5, 2015

AngularJS - How are validations implemented in Angular?

Ref:- http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers#Whatarecontrollersandneedofng-controllerandng-modelinAngular

Angular leverages HTML 5 validations and new form element types to implement validation.
For instance below is a simple form which has two text boxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.
<form name="frm1" id="frm1" >
Name :- <input type=text name="CustomerName" id="CustomerName" required />      Email :- <input type=email  name="Email" id="Email" />
<input type=submit value="Click here"/>
</form>
Below are some example of new form elements introduced in HTML 5 and Angular works with almost all of them :-
  • Color.
  • Date
  • Datetime-local
  • Email
  • Time
  • Url
  • Range
  • Telephone
  • Number
  • Search
When you run the above HTML inside a browser which understands HTML 5 , you will see your validations and form types in actions as shown in the below browser screen shot.
Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we want Angular to handle validation we need first stop HTML 5 to do validation. So for that the first step is to specify “novalidate” attribute on the form tag.
<form name="frm1" novalidate>
-----
</form>
So now the HTML will not fire those validations it will be routed to the Angular engine to further take actions.
In other words when end user fills data in the HTML UI , validation events are routed to Angular framework and depending on scenario Angular sets a field called as “$Valid”. So if the validations are fine it sets it to “True” or else its sets it to “False”.
So you can see in the below code we have attached the angular controller and models to the text boxes. Watch the code of the button it has “ng-disabled” attribute which is set via the “$Valid” property in a NEGATED fashion.
Negated fashion means when there is no error it should enable the button and when there are errors that means it’s false it should disable the button.
<form name="frm1" novalidate>
Name:-<input type=text ng-model="Customer.CustomerName" name="CustomerName" required />
Email :- <input type=email ng-model="Customer.Email" name="Email" />
<input type=submit value="Click here" ng-disabled="!(frm1.$valid)"/>
</form>
Note :- “Name” is needed for the validations to work.

How to check error validation for a specific field?

To check for a specific field you need to use the below DOM code.
!frm1.CustomerName.$valid

No comments:

Post a Comment