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:

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

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.