作者:花落酒未醉 | 来源:互联网 | 2023-05-26 18:19
我想覆盖AngularJS的电子邮件验证程序.我希望它使用我的自定义字符串来验证电子邮件地址.我在他们的文档中找到的代码是这样的:JS:
var app = angular.module('registrationApp', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
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);
}
}
}
}
});
HTML:
但代码不起作用.抛出的错误是:
TypeError:无法在N(http://ajax.googleapis.com/ajax/libs/)读取链接(http:// localhost:63342/goga_tests/js/registration.js:39:32)的undefined属性'email'.angularjs/1.2.26/angular.min.js:54:372)at g(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:256)at g(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:273)在N(http://ajax.googleapis.com/ajax/libs/angularjs /1.2.26/angular.min.js:54:313)at g(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:256) ( http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:54:313)at g(http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:47:256)在http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26 /angular.min.js:46:377
在http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:18:314
在此先感谢您的帮助!
1> PSL..:
1.2.26
您正在使用的角度版本不会$validators
在ngModel控制器实例上添加特殊属性.你需要1.3.x版本的角度.
如果您有1.3.x,您可以按原样使用您的指令,并且您可以将优先级添加2
到大于ng-model(这是1),以便您的指令在ng-model
指令轮到之前设置验证器:
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
priority: 2,
link: function(scope, elm, attrs, ctrl) {
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);
}
}
}
}
});
演示
var app = angular.module('app', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
priority: 1,
link: function(scope, elm, attrs, ctrl) {
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);
}
}
}
}
});