我正在尝试实现自定义验证以检查用户输入的条目是否有效。
EX:现有行
ORIG DEST DESK REGION
HYD MAS 20 34
情景的:
1)当用户输入具有相同值的新行时,我需要显示验证错误
2)当用户输入相同的orig,dest和不同的桌面区域时,我也需要验证错误。
我创建了自定义验证,它会检查列表中所有行的当前行,如果找到任何场景,则返回false。
我需要在ORIG或DEST或DESK或REGION的任何值更改时调用此指令,并在单个位置显示错误消息。
我试过给所有字段的指令,但是对于每个不常见的字段都会出错。
有可能这样做吗?
HTML:
<form novalidate id="ODDRForm" name="ODDRForm">
<table>
<thead>
<tr>
<th >
<span>ORIG</span>
</th>
<th >
<span>DEST</span>
</th>
<th >
<span>DESK</span>
</th>
<th >
<span>REGION</span>
</th>
</tr>
</thead>
<tbody class="tbody_border_bottom">
<tr ng-repeat="row in List" ng-form="rowForm">
<td >
<input check-duplicate type="text" name="origin" ng-model="row.orig" required /><br/>
<div ng-messages="rowForm.orig.$error" ng-if="ODDRForm.$submitted || rowForm.orig.$touched">
<span ng-message="required">Required</span>
<span ng-message="checkDuplicate">Not a valid entry</span>
</div>
</td>
<td >
<input check-duplicate type="text" name="dest" ng-model="row.dest" required /><br/>
<div ng-messages="rowForm.dest.$error" ng-if="ODDRForm.$submitted || rowForm.dest.$touched">
<span ng-message="required">Required</span>
<span ng-message="checkDuplicate">Not a valid entry</span>
</div>
</td>
<td >
<input check-duplicate type="text" name="desk" ng-model="row.desk" required /><br/>
<div ng-messages="rowForm.desk.$error" ng-if="ODDRForm.$submitted || rowForm.desk.$touched">
<span ng-message="required">Required</span>
<span ng-message="checkDuplicate">Not a valid entry</span>
</div>
</td>
<td >
<input check-duplicate type="text" name="region" ng-model="row.region" required /><br/>
<div ng-messages="rowForm.region.$error" ng-if="ODDRForm.$submitted || rowForm.region.$touched">
<span ng-message="required">Required</span>
<span ng-message="checkDuplicate">Not a valid entry</span>
</div>
</td>
</tr>
</tbody>
</table>
JavaScript的:
app.directive('checkDuplicate', [ '$http', function($http) {
return {
require : '^ngModel',
link : function(scope, element, attrs, ngModel) {
var bool = true;
ngModel.$parsers.push(function(value) {
for(var i in scope.List) {
if(scope.List[i].orig == scope.row.orig && scope.List[i].dest == scope.row.dest
&& scope.List[i].desk == scope.row.desk && scope.List[i].region == scope.row.region
&& scope.List[i].$$hashkey != scope.row.$$hashkey) {
bool = false;
}
}
ngModel.$setValidity('checkDuplicate', bool);
return value;
})
},
}
}]);
答案 0 :(得分:0)
在你的情况下没有理由添加指令,你可以只看模型更改并验证,给我示例代码我可以告诉你如何