Learn Form Validation in AngularJS

0
4806
angularjs-FormValidation

In this section, we will see how angular features provide help to make a validation in a web form. Angularjs have various property and classes on its form and its controls and we will see how these property and class helps to do validation. Validations are a way to prevent invalid data on submitting a web form.

Following are the inbuilt Angular property and classes that can be used for form a validation.

Property        CSS Class Description
$valid ng-valid Return as true, if all the form elements are valid
$invalid ng-invalid Return as true, if one of form element is invalid
$touched ng-touched Return as true, if control has blurred
$dirty ng-dirty Return as true, if user interacted with the form
$pristine ng-pristine Return as true, if user has not interacted the form

Let’s explore above property in an example, we will do client side validation with the help of above inbuilt property.

Syntax for Angular validation property
Following is a simple syntax of invoking validation property inside form html contents.

Example:

1) $Valid and $Invalid
$valid return as Boolean, in following figure you can see that form valid returning false, because the form element “Name” input box is empty , hence it is invalid because user not fill the name yet.


But, in above image form invalid returning true, because form element is invalid or Name is not fill by user. As user enter the name form valid will return true.
second

Code

2) $dirty and $pristine
The $dirty property return true in case user has interacted with the control. Its opposite property called $pristine.
Here is the syntax of invoking $dirty property, in this example we are using eduform as  form name with its control called email.

Let’s consider following image.


As you consider above image, form returning true because its control element email address is not interacted by user yet. This property called Pristine. But as you enter email address this property will return to false. Or you can say that such property called $dirty when user interacted with the form element.
four

Ultimate Java Development and Certification Course

3) $touched
The $touched property return true when its associate form element has been blurred while form submitting.
Here is the syntax of invoking $touched property, in this example we are using eduform as  form name with its control called email.

Complete Code
In this example I am making validation on email address and first name.

Output


Summary
Angular inbuilt form property helps to do client side validation, Such as valid, invalid, dirty and, pristine. With invoking this property form prevent to submit invalid/wrong data from user.

LEAVE A REPLY

Please enter your comment!
Please enter your name here