[英]Custom validation on Angular Form - on blur
在Angular中,我试图验证模糊字段的值。 我有一个客户列表,我想检查字段中的模型值是否在我的客户列表中。 如果不是,我想将有效性设置为false。
我知道ng-model-options="{updateOn: 'blur'}
存在,但是我不能使用它,因为该字段是预先输入的,因此它必须根据模型进行更新。模糊。
答案似乎是:
将其作为函数编写在控制器中,并像在指令中一样使用$ setValidity。 使用ng-blur在输入字段中触发功能。
-但是,我不断遇到一些示例,其中仅将自定义验证(如果模型值与列表中的值不匹配,则使字段无效)仅作为指令编写。 是否有作为功能编写的自定义验证示例?
编写仅在模糊时触发的指令。
但是,我找不到能做这两种事情的例子。 是否有人将自定义验证作为函数或仅在字段模糊时更新的指令作为示例?
我发现此链接对于自定义验证非常有帮助,但是在函数和指令之间的区别上,我仍然遇到相同的问题: 如何将自定义验证添加到AngularJS表单?
最近我们一直在努力:
<form name='vm.formName' id='vm.formName' novalidate>
<input type='text' id='textField' name='textField' ng-blur='vm.blurMethod()' ng-model='vm.model.text' />
// The submit is only here for show;
<input type='submit' id='submit' ng-click='vm.submitForm()' />
</form>
在控制器中:
blurMethod() {
if (this.formName.textField.$viewValue !== myArbitraryValue) {
// $setValidity called on the form, setting the textfield's validity to false
// then you can have your own validators show the error in the template
this.formName.$setValidity('textField', false);
}
}
那是我的头上的问题,将在早上看一下它是否反映了我们一直在使用的内容。 现在更新了$ setValidity调用。
假设您使用的是controllerAs:'vm'语法,这就是表单具有名称'vm.formname'且控制器使用'this'的原因。
我已经使用ui-bootstrap进行预输入,并对您的验证ui-bootstrap进行了很多控制
编辑-代码示例
<input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control" typeahead-no-results="$scope.matchFail"> <div ng-show="$scope.matchFail">Not on list!!</div>
当您选择不在列表中的值时,将显示div
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.