Using ng-pattern for custom regex validations

Loading

In AngularJS, the ng-pattern directive allows you to apply custom regular expressions (regex) to form inputs. This feature is useful when you need to validate a field against a pattern that’s more complex than the default validation rules like ng-required or ng-email. With ng-pattern, you can ensure that user input matches your custom regex patterns, such as validating phone numbers, zip codes, or even more complex formats like passwords.

In this guide, we will cover how to use ng-pattern for custom regex validations in AngularJS. We’ll go through the steps with examples of validating different types of inputs using regex.


1. Basic Setup for AngularJS Application

Before starting with regex validation, let’s set up a basic AngularJS application. Create a new HTML file and include AngularJS:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="FormController">
<form name="myForm" ng-submit="submitForm()" novalidate>
<!-- Dynamic form will be generated here -->
</form>
</body>
</html>

In the app.js file, define your AngularJS module and controller:

angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.formData = {};

// Define custom patterns for validation
$scope.regexPatterns = {
phone: /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/, // Example: 123-456-7890
email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/, // Basic email validation
password: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, // Minimum 8 characters, 1 letter, 1 number
zipCode: /^[0-9]{5}(?:-[0-9]{4})?$/ // Example: 12345 or 12345-6789
};

// A function to check if the form is valid
$scope.isFormValid = function() {
return $scope.myForm.$valid;
};

// Function to submit the form
$scope.submitForm = function() {
if ($scope.myForm.$valid) {
alert('Form submitted successfully!');
} else {
alert('Form is invalid.');
}
};
});

In this setup, we’re defining some custom regex patterns (phone, email, password, zipCode) to be used for input validation.


2. Using ng-pattern for Custom Regex Validation

Now, we will use the ng-pattern directive to apply these regular expressions to the form fields. This allows us to validate the user’s input based on the specified regex.

Phone Number Validation

Let’s start with validating a phone number. We want to validate a phone number in the format 123-456-7890.

<div>
<label for="phone">Phone Number:</label>
<input type="tel" name="phone" ng-model="formData.phone" ng-pattern="regexPatterns.phone" required class="form-control" />
<span class="error" ng-show="myForm.phone.$error.required && myForm.phone.$dirty">Phone number is required.</span>
<span class="error" ng-show="myForm.phone.$error.pattern && myForm.phone.$dirty">Invalid phone number format. (Example: 123-456-7890)</span>
</div>

Here:

  • The ng-pattern="regexPatterns.phone" directive binds the input field to the phone regex pattern.
  • The ng-show directive is used to display an error message if the input is either required but empty or doesn’t match the pattern.

Email Validation

Next, let’s validate an email address. We’ll use a basic email validation regex:

<div>
<label for="email">Email:</label>
<input type="email" name="email" ng-model="formData.email" ng-pattern="regexPatterns.email" required class="form-control" />
<span class="error" ng-show="myForm.email.$error.required && myForm.email.$dirty">Email is required.</span>
<span class="error" ng-show="myForm.email.$error.pattern && myForm.email.$dirty">Invalid email format.</span>
</div>
  • Here, the regex for email is applied with the ng-pattern directive. This pattern will ensure the entered value matches a basic email format.
  • Error messages are displayed if the email input is invalid.

Password Validation

For password validation, let’s require that the password contains at least 8 characters, with at least one letter and one number.

<div>
<label for="password">Password:</label>
<input type="password" name="password" ng-model="formData.password" ng-pattern="regexPatterns.password" required class="form-control" />
<span class="error" ng-show="myForm.password.$error.required && myForm.password.$dirty">Password is required.</span>
<span class="error" ng-show="myForm.password.$error.pattern && myForm.password.$dirty">Password must be at least 8 characters long and include at least one letter and one number.</span>
</div>
  • The regex pattern for passwords ensures that the entered password is at least 8 characters long and contains both letters and numbers.
  • Error messages are displayed for required fields and invalid patterns.

Zip Code Validation

Let’s validate a zip code. The regex we use will allow either a 5-digit zip code or a zip code with a 4-digit extension (12345-6789).

<div>
<label for="zipCode">Zip Code:</label>
<input type="text" name="zipCode" ng-model="formData.zipCode" ng-pattern="regexPatterns.zipCode" required class="form-control" />
<span class="error" ng-show="myForm.zipCode.$error.required && myForm.zipCode.$dirty">Zip code is required.</span>
<span class="error" ng-show="myForm.zipCode.$error.pattern && myForm.zipCode.$dirty">Invalid zip code format. (Example: 12345 or 12345-6789)</span>
</div>
  • The regex here checks if the zip code is either a 5-digit code or a 5-digit code with a 4-digit extension.
  • Error messages are shown when the zip code does not match the pattern or is missing.

3. Adding Form Submission Logic

In the form submission section, we check if the form is valid before proceeding with the submission:

<button type="submit" ng-disabled="!isFormValid()">Submit</button>

Here, the submit button is disabled if the form is not valid, ensuring the user cannot submit invalid data.

Leave a Reply

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