AngularJS Forms: Validation and Error Handling

AngularJS provides built-in form validation and error handling features that make it easy to validate user input and display error messages.

1. Form Validation:
– AngularJS provides various directives to validate form fields, such as `ng-required`, `ng-minlength`, `ng-maxlength`, `ng-pattern`, etc.
– These directives can be added to form fields to specify the validation rules.
– AngularJS automatically adds CSS classes (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, etc.) to the form fields based on their validation status.
– You can also use the `$valid` and `$invalid` properties of the form and form fields to check their validation status programmatically.

2. Error Handling:
– AngularJS provides the `ng-messages` directive to display error messages for form fields.
– The `ng-messages` directive can be used to show different error messages based on the validation status of a form field.
– You can use the `ng-message` directive inside `ng-messages` to define specific error messages for different validation errors.
– AngularJS automatically shows and hides the error messages based on the validation status of the form field.

Example:

<code>html
&lt;form name=&quot;myForm&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;username&quot; ng-model=&quot;user.username&quot; ng-minlength=&quot;5&quot; ng-maxlength=&quot;10&quot; required&gt;
&lt;div ng-messages=&quot;myForm.username.$error&quot; ng-show=&quot;myForm.username.$dirty&quot;&gt;
&lt;div ng-message=&quot;required&quot;&gt;Username is required.&lt;/div&gt;
&lt;div ng-message=&quot;minlength&quot;&gt;Username should be at least 5 characters long.&lt;/div&gt;
&lt;div ng-message=&quot;maxlength&quot;&gt;Username should not exceed 10 characters.&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
</code>

In the above example, the `ng-minlength`, `ng-maxlength`, and `required` directives are used to validate the `username` field. The `ng-messages` directive is used to display error messages based on the validation status of the field.

Note: Make sure to include the `ngMessages` module in your AngularJS application to use the `ng-messages` directive.

Overall, AngularJS provides a powerful and flexible way to handle form validation and error messages, making it easier to create robust and user-friendly forms.