Javascript 使用AngularJS验证具有互斥字段的表单
我正在使用AngularJS创建一个web应用程序,我有一个表单,其中有两个字段应该被验证为互斥的。我的意思是要么填写一个字段,要么填写另一个字段,但不能同时填写两个字段(如果两个字段都未填写,则也有效)。我的表格(真实案例的简化模型)如下所示:Javascript 使用AngularJS验证具有互斥字段的表单,javascript,html,angularjs,validation,Javascript,Html,Angularjs,Validation,我正在使用AngularJS创建一个web应用程序,我有一个表单,其中有两个字段应该被验证为互斥的。我的意思是要么填写一个字段,要么填写另一个字段,但不能同时填写两个字段(如果两个字段都未填写,则也有效)。我的表格(真实案例的简化模型)如下所示: <form id="form1" name="form1"> <p> <input type="text" id="field1" name="field1" ng-model="model.item1"
<form id="form1" name="form1">
<p>
<input type="text" id="field1" name="field1" ng-model="model.item1" not-both-filled="model.item2" />
</p>
<p>
<input type="text" id="field2" name="field2" ng-model="model.item2" not-both-filled="model.item1" />
</p>
<p ng-show="form1.$invalid">not valid</p>
<p ng-show="!form1.$invalid">valid</p>
</form>
angular.module('myApp', []).directive('notBothFilled', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var validateNotBothFilled = function(value) {
var theOther = scope.$eval(attrs.notBothFilled);
var isNotValid = (value && value !== '' && theOther && theOther !== '');
ctrl.$setValidity('field1', !isNotValid);
ctrl.$setValidity('field2', !isNotValid);
return value;
};
ctrl.$parsers.unshift(validateNotBothFilled);
ctrl.$formatters.unshift(validateNotBothFilled);
}
};
});
但是,这存在以下问题:
k6ps您的主要问题是以下两行:
ctrl.$setValidity('field1', !isNotValid);
ctrl.$setValidity('field2', !isNotValid);
这两行实际上设置了相同输入字段的两个自定义有效性,您需要以某种方式让另一个输入字段的ngModelController设置其有效性
试试这个:
<form id="form1" name="form1">
<p>
<input type="text" id="field1" name="field1" ng-model="model.item1" not-both-filled="field2" form="form1"/>
//I pass the field name instead and also the form where these inputs are defined.
</p>
<p>
<input type="text" id="field2" name="field2" ng-model="model.item2" not-both-filled="field1" form="form1"/>
</p>
<p ng-show="form1.$invalid">not valid</p>
<p ng-show="!form1.$invalid">valid</p>
</form>
angular.module('myApp', []).directive('notBothFilled', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var validateNotBothFilled = function(value) {
var form = scope[attrs.form];
var theOther = form[attrs.notBothFilled];
var isNotValid = (value && value !== '' && theOther.$modelValue && theOther.$modelValue !== '');
ctrl.$setValidity('field', !isNotValid);//set validity of the current element
theOther.$setValidity('field', !isNotValid);//set validity of the other element.
return value;
};
ctrl.$parsers.unshift(validateNotBothFilled);
}
};
});