How to validate email id in angularJs using ng-pattern

RegexAngularjsEmailAngularjs DirectiveNg Pattern

Regex Problem Overview


Am trying to validate an Email id field in angularJs using ng-pattern directive.

But am new to AngularJs. I need to show an error message as soon as the user enters the wrong email id.

The code which I have below is am trying to solve. Help me out with using ng-pattern for getting the proper result.

<script type="text/javascript" src="/Login/script/ang.js"></script>
<script type="text/javascript">
    function Ctrl($scope) {
        $scope.text = 'enter email';
        $scope.word = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
    }
</script>
    </head>
<body>
    <form name="myform" ng-controller="Ctrl">
        <input type="text" ng-pattern="word" name="email">
        <span class="error" ng-show="myform.email.$error.pattern">
            invalid email!
        </span>
        <input type="submit" value="submit">
    </form>
</body>

Regex Solutions


Solution 1 - Regex

If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.

Here is the example from original documentation:

<script>
function Ctrl($scope) {
  $scope.text = '[email protected]';
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" required>
  <br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
  <span class="error" ng-show="myForm.input.$error.email">
    Not valid email!</span>
  <br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>

For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D

Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info

UPD:

If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the [documentation][1] the error message can be displayed like this:

> The validator sets the pattern error key if the ngModel.$viewValue > does not match a RegExp

<script>
function Ctrl($scope) {
  $scope.text = '[email protected]';
  $scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
  Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
  <br/><br/>
  <span class="error" ng-show="myForm.input.$error.required">
    Required!
  </span><br/>
  <span class="error" ng-show="myForm.input.$error.pattern">
    Not valid email!
  </span>
  <br><br>
  <tt>text = {{text}}</tt><br/>
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  <tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>

Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview

[1]: https://docs.angularjs.org/api/ng/directive/ngPattern "documentation"

Solution 2 - Regex

There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, elm, attrs, ctrl) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (ctrl && ctrl.$validators.email) {

        // this will overwrite the default Angular email validator
        ctrl.$validators.email = function(modelValue) {
          return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
        };
      }
    }
  };
});

And simply add

<input type='email' validate-email name='email' id='email' ng-model='email' required>  

Solution 3 - Regex

According to the answer of @scx ,I created a validation for GUI

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

And simply add :

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>

Solution 4 - Regex

This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.

var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

Source.

Solution 5 - Regex

You can use ng-messages

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>

include the module

 angular.module("blank",['ngMessages']

in html

<input type="email" name="email" class="form-control" placeholder="email" ng-model="email" required>
<div ng-messages="myForm.email.$error">
<div ng-message="required">This field is required</div>
<div ng-message="email">Your email address is invalid</div>
</div>

Solution 6 - Regex

Below is the fully qualified pattern for email validation.

<input type="text" pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]*\.([a-z]{2,4})$/" ng-model="emailid" name="emailid"/>

<div ng-message="pattern">Please enter valid email address</div>

Solution 7 - Regex

Now, Angular 4 has email validator built-in https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709

Just add email to the tag. For example

  <form #f="ngForm">
    <input type="email" ngModel name="email" required email>
    <button [disabled]="!f.valid">Submit</button>
    <p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
  </form>

Solution 8 - Regex

angularjs controller way, just an example to look for one or more email in the body of a message.

sp = $scope.messagebody; // email message body
		
if (sp != null && sp.match(/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+/)) {   
console.log('Error. You are not allowed to have an email in the message body');
}

Solution 9 - Regex

I tried @Joanna's method and tested on the following websites and it didn't work.

  1. https://regex101.com/
  2. https://www.regextester.com/
  3. https://regexr.com/

I then modified it to and it worked.

/([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+

Solution 10 - Regex

I have tried wit the below regex it is working fine.

Email validation : \w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*

Solution 11 - Regex

Spend some time to make it working for me.

Requirement:

single or comma separated list of e-mails with domains ending [email protected] or [email protected]

Controller:

$scope.email = {
   EMAIL_FORMAT:  /^\w+([\.-]?\w+)*@(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*@(list.)?gmail.com)*$/,
   EMAIL_FORMAT_HELP: "format as '[email protected]' or comma separated '[email protected], [email protected]'"
};

HTML:

<ng-form name="emailModal">
    <div class="form-group row mb-3">
        <label for="to" class="col-sm-2 text-right col-form-label">
            <span class="form-required">*</span>
            To
        </label>
        <div class="col-sm-9">
            <input class="form-control" id="to"
                   name="To"
                   ng-required="true"
                   ng-pattern="email.EMAIL_FORMAT"
                   placeholder="{{email.EMAIL_FORMAT_HELP}}"
                   ng-model="mail.to"/>
            <small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
        </div>
    </div>
</ng-form>

I found good online regex testing tool. Covered my regex with tests:

https://regex101.com/r/Dg2iAZ/6/tests

Solution 12 - Regex

Use below regular expression

^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+)+((\.)[a-z]{2,})+$

It allows

test@test.com
test@test.co.in
test@test.gov.us
test@test.net
test@test.software

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanonView Question on Stackoverflow
Solution 1 - RegexSunnyMagadanView Answer on Stackoverflow
Solution 2 - RegexscxView Answer on Stackoverflow
Solution 3 - Regexvanduc1102View Answer on Stackoverflow
Solution 4 - RegexEhtesham ShamiView Answer on Stackoverflow
Solution 5 - Regexarun-rView Answer on Stackoverflow
Solution 6 - RegexSanjeev SinhaView Answer on Stackoverflow
Solution 7 - Regexso-random-dudeView Answer on Stackoverflow
Solution 8 - RegexRobot70View Answer on Stackoverflow
Solution 9 - RegexGaganView Answer on Stackoverflow
Solution 10 - RegexsubhashisView Answer on Stackoverflow
Solution 11 - RegexDmitri AlgazinView Answer on Stackoverflow
Solution 12 - RegexAnkur RaiyaniView Answer on Stackoverflow