In this demo, we will discuss about the form validation in angular js. 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 angularjs.
Requirements of form fields
These are the validation we have to implement in our form fields.
AngularJS includes the following validation directives.
Directive | Description |
---|---|
ng-required | Sets required attribute on an input field. |
ng-minlength | Sets minlength attribute on an input field. |
ng-maxlength | Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric value, allows view values of any length. |
ng-pattern | Sets pattern validation error key if the ngModel value does not match the specified RegEx expression. |
Angular includes properties which return the state of form and input controls. The state of the form and control changes based on the user's interaction and validation errors. Below listed built-in properties can be accessed using form name or input control name. To check the form status use formName.propertyName
, and to check the state of input control, use formName.inputFieldName.propertyName
.
Lists the state properties.
Property | Description |
---|---|
$error | $error object contains all the validation attributes applied to the specified element. |
$pristine | Returns true if the user has not interacted with control yet else returns false. |
$valid | Returns true if the model is valid |
$invalid | Returns true if the model is invalid |
$dirty | Returns true if user changed the value of model at least once |
$touched | Returns true if the user has tabbed out from the control. |
$untouched | Returns true if the user has not tabbed out from the control. |
Now let's have a look on demo code step by step. So have a look on the html form.
Let's understand the above example step by step:
Now have a look on the angular part(script.js).
In the above code, only app declration is there and basic controller is defined.
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!!