Alexander Gorelik
Alexander Gorelik

Reputation: 4385

Angular email custom with regular validation

I need to perform two steps in order to validate email. First i want to use angular

 type="email"

in order to check email validity then i want to use custom directive in order to send this email to server to perform some checks there.

custom validation direcitve code:

angular.module('app.register')
.directive('emailAvailable',['registerResource', function(registerResource) {
return {

    restrict: 'A',

    require: 'ngModel',

    link: function(scope, element, attr, ctrl) {
        function customValidator(ngModelValue) {
            registerResource.emailAvailable.save({"email": ngModelValue},
                function(response){
                    // Show that email is valid
                },
                function(response){
                   // Show that email is not valid
                });
            return ngModelValue;
        }
        ctrl.$parsers.push(customValidator);
    }
};

My question how to execute my customValidator function after angular type="email" is checked for validity.

Upvotes: 2

Views: 816

Answers (1)

Pedro Nascimento
Pedro Nascimento

Reputation: 13886

Using a custom validator, you can do something like this:

  var app = angular.module('form-example1', []);
  // only allows e-mail from google
  var EMAIL_REGEXP = /^[a-z0-9](\.?[a-z0-9]){5,}@g(oogle)?mail\.com$/;
  app.directive('email', function() {
    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
        ctrl.$validators.email = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
            // consider empty models to be valid
            return true;
          }

          if (EMAIL_REGEXP.test(viewValue)) {
            // it is valid
            return true;
          }

          // it is invalid
          return false;
        };
      }
    };
  });

Working example here.

Upvotes: 3

Related Questions