Showing error messages dynamically in forms

Loading

What You’ll Learn

How AngularJS handles form validation
Using $dirty, $touched, and $invalid for error handling
Displaying error messages dynamically
Best practices for better user experience


1️⃣ Understanding AngularJS Form Validation

AngularJS automatically tracks form and input field states using properties like:

PropertyDescription
$dirtyThe field has been modified.
$touchedThe field has been clicked or focused at least once.
$invalidThe field contains an invalid value.
$pristineThe field has not been modified.

These properties allow us to show error messages only when necessary.


2️⃣ Basic AngularJS Form with Validation

Let’s create a simple form that validates name, email, and phone number.

HTML Form with Dynamic Error Messages

<div ng-app="myApp" ng-controller="FormController">
<form name="userForm" novalidate>

<!-- Name Field -->
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required />
<span class="error" ng-show="userForm.name.$dirty && userForm.name.$error.required">
Name is required.
</span>

<!-- Email Field -->
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required />
<span class="error" ng-show="userForm.email.$dirty && userForm.email.$error.required">
Email is required.
</span>
<span class="error" ng-show="userForm.email.$dirty && userForm.email.$error.email">
Enter a valid email address.
</span>

<!-- Phone Number Field -->
<label>Phone:</label>
<input type="text" name="phone" ng-model="user.phone" ng-pattern="/^\d{10}$/" required />
<span class="error" ng-show="userForm.phone.$dirty && userForm.phone.$error.required">
Phone number is required.
</span>
<span class="error" ng-show="userForm.phone.$dirty && userForm.phone.$error.pattern">
Enter a valid 10-digit phone number.
</span>

<br />
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>

🔹 CSS for Styling the Errors

.error {
color: red;
font-size: 12px;
}

3️⃣ How It Works

ng-show="userForm.name.$dirty && userForm.name.$error.required"

  • Shows an error only if the field is modified ($dirty) and empty ($error.required).
    $error.email and $error.pattern help display specific error messages.
    The submit button is disabled when the form is invalid (ng-disabled="userForm.$invalid").

4️⃣ Best Practices for Error Handling

Use $touched instead of $dirty if you want errors to appear after clicking the field once.
Combine multiple errors using ng-messages (for better readability).
Always provide clear and user-friendly messages.
Keep the error styling consistent for better UX.

Leave a Reply

Your email address will not be published. Required fields are marked *