[regex] How to validate email id in angularJs using ng-pattern

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>

This question is related to regex angularjs email angularjs-directive ng-pattern

The answer is


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.


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');
}

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


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>

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

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


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>

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>  

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>

Use below regular expression

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

It allows

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

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+

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>

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to angularjs-directive

Angular2 - Input Field To Accept Only Numbers Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS ng-change not working on a text input Controller not a function, got undefined, while defining controllers globally Find child element in AngularJS directive Angular directives - when and how to use compile, controller, pre-link and post-link How to validate email id in angularJs using ng-pattern Enable/Disable Anchor Tags using AngularJS get original element from ng-click How to detect browser using angularjs?

Examples related to ng-pattern

How to validate email id in angularJs using ng-pattern