0

I'm trying to override the e-mail validator from AngularJS, but I can't seem to get it to work properly.

This is the code that I have for the JavaScript file:

var app = angular.module("home", []);


app.directive("overwriteEmail", function() {
var UEMAIL_REGEX = /^[a-z0-9]+@university\.edu$/i;
 return {
   require: "ngModel",
   restrict: "",
   link: function(scope, elm, attrs, ctrl) {
   if (ctrl && ctrl.$validators.email) {
   ctrl.$validators.email = function(modelValue) {
     return ctrl.$isEmpty(modelValue) || UEMAIL_REGEX.test(modelValue);
   };

 }

}
 };


});

For the HTML file I have this:

<label>University Email Address:</label>
<input type="email" overwrite-email name="uemail" data-ng-model="email" placeholder="University e-mail required" required>
<span class="warning" data-ng-show="regis.uemail.$error.email">Invalid email!</span>

My code validates up to the @ sign, then it doesn't seem to care what comes after the @ symbol. What approach can I take to fix this problem?

1 Answer 1

1

You can use priority:2 which is greater than ng-model having priority:1 :-) it may override the email property.

app.directive("overwriteEmail", function() {
var UEMAIL_REGEX = /^[a-z0-9]+@university\.edu$/i;
 return {
   require: "ngModel",
   restrict: "",
   priority:2,
   link: function(scope, elm, attrs, ctrl) {
   if (ctrl && ctrl.$validators.email) {
   ctrl.$validators.email = function(modelValue) {
     return ctrl.$isEmpty(modelValue) || UEMAIL_REGEX.test(modelValue);
   };

 }

}
 };

Ps:-Provided you have 1.3.x

Sign up to request clarification or add additional context in comments.

1 Comment

I just realized that I was using version 1.2.x instead of 1.3.x. The above code works without priority in version 1.3.x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.