Angular JS Email Validation with unicode characters

后端 未结 5 730
日久生厌
日久生厌 2021-01-05 08:45

I have a sign up form for an application, and angular js is responsible for its validation.

I ran into an issue when Angular js wasn\'t accepting an email address wh

相关标签:
5条回答
  • 2021-01-05 09:18

    AngularJS uses this regular expression to test email: https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L4

    What you could do is write a directive that checks it yourself. Just copy the one from AngularJS and use your own regexp: https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L606-L614

    myApp.directive('nanuEmail', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elm, attrs, model) {
          //change this:
          var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
          var emailValidator = function(value) {
          if (!value || EMAIL_REGEXP.test(value)) {
            model.$setValidity('email', true);
            return value;
          } else {
            model.$setValidity('email', false);
            return undefined;
          }
          model.$parsers.push(emailValidator);
          model.$formatters.push(emailValidator);
        }
      };
    });
    

    Then you can just do:

    <input nanu-email ng-model="userEmail">
    
    0 讨论(0)
  • 2021-01-05 09:21

    I just updated the regex in the angular.js file (added " ' " in the expression) and it worked, without making any other changes.

    EMAIL_REGEXP = /^[A-Za-z0-9._%+-']+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}$/ . Thanks Vittore, for giving me the idea to update REGEX. :)

    0 讨论(0)
  • 2021-01-05 09:23

    why do you return undefined?

    Refactoring of the function:

    var verificationEmail = function (viewValue) {
      if ((typeof viewValue != "undefined") && viewValue != "") {
        return regex.test(viewValue);
      }
    };
    
    0 讨论(0)
  • 2021-01-05 09:30

    If having html5 <input type=email /> is not critical, you can use <input type=text /> and pattern validation

     <input type="text" ng-model="field" ng-pattern="EMAIL_REGEXP" />
    

    and you can use regex that @Andy Joslin posted in his answer

     $scope.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;
    
    0 讨论(0)
  • 2021-01-05 09:35

    Angular do not support the apostrophe(') in email Id. If you need to validate the apostrophe in Angular, you need to change the regular expression from:

    (/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)
    

    To:

    /^[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/.
    

    It will work perfectly.

    0 讨论(0)
提交回复
热议问题