【发布时间】:2016-06-17 14:29:50
【问题描述】:
我正在尝试实施自定义验证来检查用户输入的条目是否有效。
EX:现有行
ORIG DEST 区域
HYD MAS 20 34
场景:
1)当用户输入具有相同值的新行时,我需要显示验证错误。
2)当用户输入相同的orig,dest和region不同的桌子时,我也需要验证错误。
我创建了自定义验证,它将检查当前行以及列表中的所有行,如果发现任何场景,则返回 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;
})
},
}
}]);
【问题讨论】:
标签: angularjs validation angular-directive