AngularJS Form Validation (original) (raw)
Last Updated : 26 Aug, 2022
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not. Form input fields have the following states:
- $untouched: It shows that field has not been touched yet.
- $touched: It shows that field has been touched.
- $pristine: It represents that the field has not been modified yet.
- $dirty: It illustrates that the field has been modified.
- $invalid: It specifies that the field content is not valid.
- $valid: It specifies that the field content is valid.
These all are the properties of the input field which can be either true or false. Forms have the following states:
- $pristine: It represents that the fields have not been modified yet.
- $dirty: It illustrates that one or more fields have been modified.
- $invalid: It specifies that the form content is not valid.
- $valid: It specifies that the form content is valid.
- $submitted: It specifies that the form is submitted.
These all are the properties of the form which can be either true or false. These states can be used to show meaningful messages to the user.
Example 1: This example describes the AngularJS Form Validation, where the ng-show directive is utilized to display the required warning message for the inappropriate or incorrect input.
HTML `
AngularJS Form ValidationGeeksforGeeks
AngularJS Form Validation
Name: The name is required.
Address:
We use the ng-show directive to only
show the error message
if the field
has not modified yet AND content present
in the field is invalid.
`
Output:
Custom validation: To create your own validation function add a new directive to your application, and deal with the validation inside a function with certain specified arguments.
Example 2: This example describes the AngularJS Custom Form Validation by creating our own directive, containing a custom validation function, and refer to it by using app-directive. The field will only be valid if the value is greater than or equal to 18.
HTML `
AngularJS Form ValidationGeeksforGeeks
AngularJS Custom Form Validation
Username:Age:
The input's valid state is:
{{form1.userage.$valid}}
Note: The input field must have user age greater than 18 to be considered valid for voting.
`
Output: