AngularJS Validation
- The AngularJS provides many additional supports such as validation, data-binding to the HTML form.
- These are the input elements used in HTML form and these are validated by using AngularJS.
- <button> element.
- <input> element.
- <select> element.
- <textarea> element.
- AngularJS Validations are client-side validation, so we should use the server side validation for security aspects.
Sample code for Form Validation in AngularJS:
Code Explanation for Form validation in AngularJS:
- The “myform” is name of the form.
- The “required” attribute is used to specify the textbox should not be empty on form submission.
- The “ng-minlength” is used to specify the textbox should have minimum length 10 characters.
- The “ng-change” is used to call the function changefun() when the value of textbox is changed.
- The “ng-maxlength” is used to specify the textbox should not exceed maximum length 13 characters.
- The “ng-pattern” is used to specify the textbox should match the pattern specified in the regex.
- The “$dirty” is used to check the textbox has been modified or not.
- The “$invalid” is used to check the textbox whether it has been modified or not.
- The <span> is used to display the warning on the required field error.
- The <span> is used to display the warning on pattern error.
- The <span> is used to display the warning on minlength error.
- The <span> is used to display the warning on maxlength error.
- The “$valid” is used to specify the textbox value should be valid.
- The “mychange” is used to bind the mychange variable value.
- The “changefun” is used to set the mychange value as “text changed”.
Sample Output for Form validation in AngularJS:
- The form is displayed on page load.
- If the textbox is empty then the required field error shows the warning.
- If the textbox does not match the pattern then the pattern error shows the warning.
- If the textbox does not have the minimum character then the minlength error shows the warning.
- If the textbox exceed the maximum character length then the maxlength error shows the warning.
- When user enters valid mobile number there is no warning displayed.
- Valid Number text shows when the $valid is true.
- “text changed” shows when the user change the textbox value.