Updated on Kisan Patel
Validating HTML form controls and providing validation messages to users is very important. To provide the best experience, users should be immediately notified about any errors and allowed to correct them.
AngularJS provide a well-defined API to validate the field, format or parse the values, track the field state, etc.
You need to validate the form client-side using HTML5 form attributes. Lets add some HTML5 attributes to make the input required:
<div ng-app="app" ng-controller="studentController"> <form name="myForm" ng-submit="submit()" > <p> <label>Name</label> <input type="text" name="name" ng-model="student.Name" ng-required="true" /> <span class="error-message" ng-show="myForm.name.$dirty && myForm.name.$error.required">The Name is Mandatory</span> </p> <p> <label>Roll No.</label> <input type="text" name="rollno" ng-pattern="/^\d{10}$/" ng-model="student.RollNo" ng-required="true" /> <span class="error-message" ng-show="myForm.rollno.$dirty && myForm.rollno.$error.required">The Roll No. is Mandatory</span> <span class="error-message" ng-show="myForm.rollno.$dirty && myForm.rollno.$error.pattern">The Roll No. is not valid</span> </p> <input type="submit" value="Submit" > </form> </div>
In above code, we use ng-pattern
to validate that the field contains exactly 10 digits.
AngularJS provide a built-in directives to validate form:
Directives | Description |
---|---|
ng-required | Marks the fields that are mandatory. |
ng-maxlength | Validates the maximum allowable characters in a field. |
ng-minlength | Validates the minimum allowable characters in a field. |
ng-pattern | Validates a field against a given regular expression. |
In above code, we have also use some properties that lets us track the status of our form.
$dirty: Initially, the property $dirty
is set to false. Once the user starts interacting with any of the form controls, the form becomes dirty and $dirty property is set to true.
$valid: The $valid
property of the form is set to true when all the individual fields of a form become valid.
$invalid: The $invalid
property of the form is set to true if at least one field in the form is invalid.
Next, we have use the $form.invalid
state in combination with a ng-disabled
directive to disable the Submit button as long as the form contains invalid data.
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">