Using ng-pattern and ng-messages to validate emails

Amit Singh
Jul 22, 2017 · 2 min read

AngularJS provides a set of powerful form validation options but today we will see how we can implement a regex pattern inside the input to validate for correct emails.

So to start with we need two things angularJS and ng-messages. Additionally you can use any CSS framework , these libraries play well with others.

Set up your angular application first then insert ng-messages as a dependency in your module.

angular.module('myapp',['ng-messages']);

Next in your form add ng-pattern followed by this regex pattern to check for emails


<input ng-model=”newUser.email”
type=”mail”
name=”email”
placeholder=”Email (required)”
ng-required=”true”
ng-pattern = ‘/^(([^<>()\[\]\.,;:\s@\”]+(\.[^<>()\[\]\.,;:\s@\”]+)*)|(\”.+\”))@(([^<>()[\]\.,;:\s@\”]+\.)+[^<>()[\]\.,;:\s@\”]{2,})$/i’>
<div ng-messages=”signUp.email.$error” ng-messages-multiple>
<div ng-message=”required”>This is required.</div>
<div ng-message=”pattern”>Please enter a valid email address. </div>
</div>

So what’s happening here ?

First notice ng-required=”true”. This makes the input field compulsory to be filled. Next ng-pattern followed by this long string of gibberish letters.

That long string is what does the email checking.If the user enters any email which does not follow this pattern of abc@xyz.com then we will get an error.

Enough about the errors , now how can we access these errors and do some stuffs with it — behold ng-messages.

Start with declaring a div with ng-messages="formName.feildName.$error"

In our case we have ng-messages=" signUp.email.$error "

Also add ng-messages-multiple if you want to display more than one errors.

<div ng-message=”required”>This is required.</div>
<div ng-message=”pattern”>Please enter a valid email address.</div>

The first message will show up if the user leaves the input field empty.The second when they enter an invalid email address.

So , this is how you use ng-messages with ng-pattern to validate emails.

You can also try out other regular expression patterns to get more powerful validations.

QUICK READ : https://www.wired.com/2008/08/four_regular_expressions_to_check_email_addresses/

https://scotch.io/tutorials/angularjs-form-validation

Written by

Frontend Developer at CoinSwitch , Solo Traveller

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade