【发布时间】:2017-01-05 01:55:48
【问题描述】:
我想用 required 验证下拉菜单。仅当值为 null 或空白时才需要默认值(如果我错了,请纠正我)。如果值为'未分配',我希望给出错误并使表单无效。
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required></select>
使用它我可以显示错误消息,但这确实会使表单无效
<span class="error" ng-show="applications.first == 'not assigned'?true:false">Select Approver</span>
解决方案:-
1) 如果您想使用必需,请检查 Shannon Hochkins 解决方案。
<form name="formName">
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required="true">
<option value="">Not Assigned</option>
</select>
<span class="error" ng-show="formName.first.$invalid ?true:false">Select Approver</span>
<pre>{{formName | json}}</pre>
</form>
他添加了一个空白值<option value="">Not Assigned</option> 的选项。并在选择中设置required="true"。这非常有效。
2) 使用自定义指令。
app.directive('req', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.req;
var invalid = $attrs.invalid;
if (viewValue == invalid) {
// It's valid because we have nothing to compare against
ctrl.$setValidity('req', false);
} else {
ctrl.$setValidity('req', true);
}
};
$attrs.$observe('req', function(comparisonModel) {
// Whenever the comparison model changes we'll re-validate
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
还有你的html代码:
<select invalid="not assigned" req={{applications.first}} name="first" class="select" ng-model="applications.first" ng-options="x.id as x.value for x in list1" title="Select Approver" ></select>
<span class="error" ng-show="Step5.first.$error.req">Select Approver</span>
您必须在此处设置invalid="not assigned" 或任何值,例如invalid='0' 或invalid=' '。在指令中,如果值匹配,它将与无效属性进行比较,它将显示错误。
【问题讨论】:
-
您是否尝试将下拉菜单的默认值分配给:
applications.first = null -
@ShannonHochkins 我有级联下拉菜单,我使用了过滤器让我更新我的问题。
-
请看我的回答!
-
将默认值设为 null 的问题是它会破坏其他下拉列表中的过滤器。并使其空白(没有选项)
-
查看我的演示链接,使用表单对象作为验证器时不必指定默认值
标签: html angularjs ng-required