我正在尝试编写自己的一组指令。我写了两个指令:
我想要实现的目标:
发生了什么
当我只添加eaValidateEmail指令时,一切正常,并验证了电子邮件的格式。
但是,只要我添加eaValidateUnique指令,就会省略eaValidateEmail指令,并且即使在console.log中ctrl。$ valid为false,eaValidateUnique指令的ctrl。$ valid方法也会一直传递。
我已阅读AngularJS文档,买了两本书,但这些例子总是很基础。目前我无法弄清楚问题所在的位置。看起来与ngModelController存在冲突,但我无法找到解决此问题的正确方法。
我目前正在使用ValidateCtrlNew表单进行测试。所以html表单的“新”部分中的字段。
问题:
以下是 jsfiddle :http://jsfiddle.net/charms/6j3U8/230/
<div ng-controller="ValidateCtrlNew">
<form name="user_form_new" class="pure-form" novalidate>
<fieldset>
<legend>New</legend>
<input type="text" name="email" ng-model="user.email" placeholder="E-Mail" class="txt_fld" ng-required="true" ea-validate-email ea-validate-unique/><br/>
<div class="inv_msg" ng-show="user_form_new.email.$dirty && user_form_new.email.$invalid">Invalid:
<span ng-show="user_form_new.email.$error.required">Please enter your email.</span>
<span ng-show="user_form_new.email.$error.eaValidateEmail">This is not a valid email.</span>
<span ng-show="user_form_new.email.$error.eaValidateEmailCheck">Checking email....</span>
<span ng-show="user_form_new.email.$error.eaValidateUnique">This email is already taken.</span>
</div>
</fieldset>
</form>
</div>
.directive('eaValidateUnique', ['$http', function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.push(function(viewValue) {
console.log(ctrl);
//ctrl.$setValidity('eaValidateUnique', true);
if(ctrl.$valid) {
ctrl.$setValidity('eaValidateUnique', false);
console.log("valid was true");
}
});
}
};
}])
.directive('eaValidateEmail', [function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
var EMAIL_REGEXP = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
ctrl.$parsers.push(function(viewValue) {
// set validity to true to clear out if previous validators fail
ctrl.$setValidity('eaValidateEmail', true);
if(ctrl.$valid) {
// set validity to false as we need to check the value here
ctrl.$setValidity('eaValidateEmail', false);
if(viewValue !== undefined && viewValue !== "" && EMAIL_REGEXP.test(viewValue)) {
// if the format of the email is valid then we set validity to true
ctrl.$setValidity('eaValidateEmail', true);
ctrl.$setValidity('eaValidateEmailCheck', true);
console.log("TRUE");
} else {
// if the format of the email is invalid we set validity to false
ctrl.$setValidity('eaValidateEmail', false);
ctrl.$setValidity('eaValidateEmailCheck', true);
console.log("FALSE");
}
}
return viewValue;
});
}
};
}]);
答案 0 :(得分:2)
您可以将eaValidateEmail的优先级添加到100,如..
restrict: 'A',
priority:'100',
require: 'ngModel',
答案 1 :(得分:0)
据我所知,验证器链接在$ parsers数组上。如果验证器确定值为有效,则AngularJs验证器返回值,但如果值无效,则返回undefined。
这样,您链上的其他验证器将无法再使用它了。
http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController# $解析器