Using ng-pattern for input validation

Loading

ng-pattern is a built-in directive in AngularJS that allows developers to validate user input using regular expressions (regex). It ensures that users enter data in a specific format before submission.


Topics Covered

  1. Why Use ng-pattern?
  2. Syntax of ng-pattern
  3. Common Use Cases of ng-pattern
  4. Example: Validating a Phone Number
  5. Example: Validating an Email Address
  6. Example: Validating a Password with Strength Rules
  7. Displaying Validation Messages
  8. Complete Example with Form Submission
  9. Conclusion

1. Why Use ng-pattern?

Ensures input follows a specific format
Reduces the need for additional JavaScript validation
Works seamlessly with AngularJS form validation ($valid, $error, etc.)
Enhances user experience with real-time feedback


2. Syntax of ng-pattern

<input type="text" ng-model="inputValue" ng-pattern="/regex/" required>
  • ng-pattern="/regex/" → Defines the regular expression to validate input
  • ng-model="inputValue" → Binds the input value to a model
  • required → Ensures the field is mandatory

3. Common Use Cases of ng-pattern

Use CaseRegex Pattern
Numbers Only/^\d+$/
Alphabets Only/^[a-zA-Z]+$/
Alphanumeric/^[a-zA-Z0-9]+$/
Email Format/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/
Phone Number (10 Digits)/^\d{10}$/
Password (1 Uppercase, 1 Digit, Min 8 Chars)/^(?=.*[A-Z])(?=.*\d).{8,}$/

4. Example: Validating a Phone Number

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

Ensures the user enters exactly 10 digits
Shows error message if invalid


5. Example: Validating an Email Address

<form name="emailForm">
<label>Email:</label>
<input type="email" name="email" ng-model="user.email"
ng-pattern="/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/" required>
<span ng-show="emailForm.email.$error.pattern">Invalid email format.</span>
</form>

Ensures the email follows username@domain.com format


6. Example: Validating a Password with Strength Rules

<form name="passwordForm">
<label>Password:</label>
<input type="password" name="password" ng-model="user.password"
ng-pattern="/^(?=.*[A-Z])(?=.*\d).{8,}$/" required>
<span ng-show="passwordForm.password.$error.pattern">Password must be at least 8 characters long, include 1 uppercase letter, and 1 number.</span>
</form>

Ensures password has:

  • At least 8 characters
  • 1 uppercase letter
  • 1 digit

7. Displaying Validation Messages Using ng-messages

AngularJS provides ng-messages for better error handling.

Example: Improved Error Messages for Email Validation

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.8.2/angular-messages.min.js"></script>

<form name="emailForm">
<label>Email:</label>
<input type="email" name="email" ng-model="user.email"
ng-pattern="/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/" required>
<div ng-messages="emailForm.email.$error">
<span ng-message="required">Email is required.</span>
<span ng-message="pattern">Invalid email format.</span>
</div>
</form>

Uses ng-messages to display multiple validation errors dynamically


8. Complete Example with Form Submission

Here’s a full example with phone number and password validation, error messages, and form submission handling.

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.8.2/angular-messages.min.js"></script>
</head>
<body ng-controller="FormController">

<form name="registerForm" ng-submit="submitForm()" novalidate>

<label>Phone Number:</label>
<input type="text" name="phone" ng-model="user.phone"
ng-pattern="/^\d{10}$/" required>
<div ng-messages="registerForm.phone.$error">
<span ng-message="required">Phone number is required.</span>
<span ng-message="pattern">Enter a valid 10-digit phone number.</span>
</div>

<label>Password:</label>
<input type="password" name="password" ng-model="user.password"
ng-pattern="/^(?=.*[A-Z])(?=.*\d).{8,}$/" required>
<div ng-messages="registerForm.password.$error">
<span ng-message="required">Password is required.</span>
<span ng-message="pattern">Password must be at least 8 characters, include 1 uppercase letter and 1 number.</span>
</div>

<button type="submit" ng-disabled="registerForm.$invalid">Register</button>
</form>

<script>
var app = angular.module('myApp', ['ngMessages']);

app.controller('FormController', function ($scope) {
$scope.user = {};
$scope.submitForm = function () {
if ($scope.registerForm.$valid) {
alert("Form submitted successfully!");
}
};
});
</script>

</body>
</html>

Prevents form submission if input is invalid
Displays error messages dynamically
Disables submit button if form is invalid

Leave a Reply

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