![]()
What You’ll Learn:
What is ng-pattern?
How to use ng-pattern for form validation
Common regex patterns for validation
Displaying validation messages
Best practices
1️⃣ What is ng-pattern?
The ng-pattern directive in AngularJS allows you to validate user input using regular expressions (regex). It ensures that the input matches a specified pattern before the form is considered valid.
2️⃣ Basic Syntax of ng-pattern
<input type="text" ng-model="username" ng-pattern="/^[a-zA-Z0-9]+$/" required />
Explanation:
The input will only accept alphanumeric characters (a-z, A-Z, 0-9).
If the user enters invalid characters (like @, #, !), the input will be marked as invalid.
3️⃣ Using ng-pattern for Form Validation
Let’s create a form that validates name, email, and phone number using ng-pattern.
<form name="userForm">
<!-- Name Validation: Only letters (a-z, A-Z) -->
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" ng-pattern="/^[a-zA-Z\s]+$/" required />
<span ng-show="userForm.name.$error.pattern">Invalid name! Only letters are allowed.</span>
<!-- Email Validation -->
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="userForm.email.$error.email">Invalid email format!</span>
<!-- Phone Number Validation: Only digits and 10 characters -->
<label>Phone:</label>
<input type="text" name="phone" ng-model="user.phone" ng-pattern="/^\d{10}$/" required />
<span ng-show="userForm.phone.$error.pattern">Enter a 10-digit phone number.</span>
<br />
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
4️⃣ Explanation of Regex Patterns
| Field | Pattern | Description |
|---|---|---|
| Name | /^[a-zA-Z\s]+$/ | Allows only letters (a-z, A-Z) and spaces |
| (built-in validation) | No need for ng-pattern, AngularJS handles it automatically | |
| Phone | /^\d{10}$/ | Accepts exactly 10 digits |
5️⃣ Displaying Validation Messages Dynamically
To show error messages only when the user interacts with the field, use $touched and $dirty properties.
<span ng-show="userForm.phone.$error.pattern && userForm.phone.$touched">
Invalid phone number!
</span>
Explanation:
The error message appears only if the field is touched (i.e., the user interacts and moves away).
Prevents displaying errors before user input.
