How to validate email id in angularJs using ng-pattern
Stefan Bogdanescu
Founder & Senior Architect
How to Validate Email IDs in AngularJS using ng-pattern and Modern Best Practices
As a senior developer, I often see developers struggling with form validation in older frameworks like AngularJS. While directives like ng-pattern exist, modern application development demands robust, maintainable, and highly accurate validation mechanisms. This post will guide you through validating email IDs in AngularJS, showing you how to correctly use ng-pattern, and crucially, introducing the superior, idiomatic Angular way to handle form validation.
Understanding ng-pattern in AngularJS
The ng-pattern directive in AngularJS is designed to check if the value of an input field matches a specific regular expression (regex). It's a straightforward tool for basic format checking on the client side. However, relying solely on it for complex data validation, like ensuring an email address is syntactically correct and deliverable, has limitations.
The primary mechanism involves setting the ng-pattern attribute on an input element and accessing the error state via $error.
Let's look at the code structure you provided:
<input type="text" ng-pattern="word" name="email">
<span class="error" ng-show="myform.email.$error.pattern">
invalid email!
</span>
While this setup attempts to show an error message when the pattern fails, it relies on a manually defined regex and post-processing logic. The issue lies in defining a perfect, universally accepted regex for email validation—it is notoriously complex. A simple regex often catches obvious errors but misses edge cases.
Refining the Email Validation Logic
For email validation, we need a more precise regular expression. While the example used /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/, this pattern is overly simplistic and will fail for many valid email formats. Real-world email regexes are extremely complex.
Best Practice Note: In professional development, especially when building applications that mirror robust systems—much like those found in frameworks such as Laravel—we prioritize using well-tested libraries or framework features over crafting complex custom regexes from scratch, unless absolutely necessary.
The Superior Angular Validation Approach
Instead of relying solely on ng-pattern, the recommended approach in AngularJS is to leverage the built-in validation capabilities provided by the framework. This method integrates validation directly into the model binding and error reporting system, making your code cleaner and easier to maintain.
Step-by-Step Implementation with Angular Validation
We will switch from using ng-pattern for the core validation to using a custom validator function combined with ng-model and the $error object.
1. Define the Controller and Scope: The controller should handle the logic for updating the model and setting errors.
2. Implement Custom Validation: We define a function that checks the email format against a reliable regex before allowing submission.
3. Apply Validation Directives:
Use ng-model to bind the input, and use ng-model-options or custom controls to manage error visibility based on the model's validity.
Here is an improved conceptual example demonstrating how you would structure this in AngularJS:
// In your controller setup
function Ctrl($scope) {
$scope.email = '';
$scope.emailError = false; // Initialize error state
$scope.validateEmail = function(email) {
// A more robust, albeit still simplified, regex for demonstration
var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (emailRegex.test(email)) {
$scope.emailError = false;
return true; // Valid
} else {
$scope.emailError = true;
return false; // Invalid
}
};
}
4. Update the HTML Template:
We bind the input using ng-model and use ng-show based on our custom error flag. Note how we are now explicitly checking a boolean error state rather than just relying on $error.pattern.
<form name="myform" ng-controller="Ctrl">
<!-- Use ng-model for two-way binding -->
<input type="text" ng-model="email" ng-change="validateEmail(email)">
<!-- Show error based on the custom flag -->
<span class="error" ng-show="emailError">
Please enter a valid email address!
</span>
<input type="submit" value="submit">
</form>
Conclusion
While ng-pattern is a simple tool, for critical data like email validation in an AngularJS application, adopting the framework's native validation system provides significantly better results. By implementing custom validation functions and managing error states explicitly (as shown above), you create an application that is more predictable, easier to debug, and adheres to modern development standards. As you build sophisticated applications, focusing on robust data integrity at both the front-end and back-end—much like ensuring strong data handling in systems built with Laravel principles—will save you countless headaches down the line.