【问题标题】:how to validate across two different models in angular js如何在angular js中验证两个不同的模型
【发布时间】:2018-11-13 08:33:43
【问题描述】:
谁能告诉我如何在 angularjs 中验证两个不同的模型
这是我的代码:
http://plnkr.co/edit/Utsg7Zr8fsg7zzX5Naib?p=preview我正在使用自定义指令添加自定义验证
要求
当用户输入“名字”时它应该显示错误它检查“姓氏”长度如果小于4.它应该显示错误。如果用户输入“姓氏”则在姓氏中相同然后检查“第一name”长度小于4,如果是则显示错误
我执行以下步骤:
- 在第一个字段中输入“a”(它会变成红色,这很好)。
-
但是当我在姓氏中输入“abcderff”时,为什么名字是红色的
??
.directive("testfirst", function() {
return {
restrict: "A",
require: 'ngModel',
link: function(scope, element, attributes, modelVal) {
modelVal.$validators.testfirst= function(val) {
console.log(attributes.last)
console.log((attributes.last && attributes.last.length < 4));
if(val.length > 0 && !(attributes.last && attributes.last.length < 4)){
return false
}
return true
};
scope.$watch("val", function() {
modelVal.$validate();
});
}
};
}).directive("testlast", function() {
return {
restrict: "A",
require: 'ngModel',
link: function(scope, element, attributes, modelVal) {
modelVal.$validators.testlast= function(val) {
if(val.length > 0 && !(attributes.first && attributes.first.length < 4)){
return false
}
return true
};
scope.$watch("val", function() {
modelVal.$validate();
});
}
};
});
【问题讨论】:
标签:
javascript
angularjs
angularjs-directive
【解决方案1】:
您可以参考我更改此内容:
index.html
<body ng-controller="MainCtrl">
<button ng-click="submit()">Submit</button>
<form name="myform">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th width="50%">Field Name</th>
<th class="smallcol" width="50%">Field Value</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in c">
<td ng-if="value.type == 'LABEL'" colspan="2" style="background: #777; color: white;">{{key}}</td>
<td ng-if="value.type == 'FIELD'">{{key}}</td>
<td ng-if="value.type == 'FIELD' && isEditableMode && value.editable && value.dataType=='last'">
<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
<input type="text" name="{{key}}" first="{{getCheck('First')}}" class="form-control" ng-model="value.value" ng-keyup="update(value)" testlast>
</div>
</td>
<td ng-if="value.type == 'FIELD' && isEditableMode && value.editable && value.dataType=='name'">
<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
<input type="text" last="{{getCheck('Last')}}" name="{{key}}" class="form-control" ng-model="value.value" ng-keyup="update(value)" testfirst>
</div>
</td>
</tr>
</tbody>
</table>
</form>
</body>
注意:
测试用例1:当用户输入“名字”时它应该显示错误它检查“姓氏”长度如果小于4.它应该显示错误
测试用例2:如果用户输入“姓氏”,则姓氏相同,然后检查“名字”长度是否小于4。如果是,则应显示错误
测试用例 1 完成后,您必须清除所有字段的值。
之后您将测试用例 2,因为 css 显示错误错误。你应该再处理一次。
sample code