表单验证 - 需要一组中的一个 [英] Form validation - Required one of many in a group
问题描述
在我目前正在处理的项目中,我目前有三个文本框,我需要验证是否至少填充了一个文本框.
In the project I'm working on at the moment I currently have three textboxes and I need to validate that at least one of the text boxes has been populated.
我一直在阅读 Angular 指令的自定义验证,我知道您可以使用以下方法在指令的链接函数中设置输入的有效性:
I've been reading into custom validation with Angular directives and I understand you can set the validity of an input in a directive's link function using the following:
ctrl.$parsers.unshift(function(viewValue) {
// validation logic here
});
我遇到的问题是我不需要设置单个输入的有效性.如果不满足条件,我需要使整个表单无效.我只是想知道如何解决这个问题?
The problem I have is that I don't need to set an individual input's validity.. I need to invalidate the entire form if the criteria isn't met. I just wonder how to approach this?
我在想也许我应该创建一个指令,放在封闭的表单本身上,然后使表单无效?
I'm thinking maybe I should create a directive that's placed on the enclosing form itself and then make the form invalid?
我想我只是在寻找有关我应该如何处理的一些指导,因为我有点不清楚从哪里开始 - 我正在阅读的有关自定义验证的所有材料似乎都是在您进行验证时使用的与表单上的一组条件相对的特定输入.
I suppose I'm just looking for some guidance into how I should go about this because I'm a little unclear where to start - all the material I'm reading on custom validation seems to be for when you're validating a specific input as opposed to a set of conditions on a form.
我希望我已经说清楚了!谢谢..
I hope I've made myself clear! Thanks..
推荐答案
您可以使用 ng-required 通过检查字符串的长度属性来强制用户至少填写一个字段.
You can use ng-required to force the user to fill at least one field by checkingthe length attribute of the string.
例如,您可以执行以下操作:
You can do the following for example:
<form name="myForm">
<input type="text" ng-model="fields.one" name="firstField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />
<br/>
<input type="text" name="secondField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" ng-model="fields.two" />
<br/>
<input type="text" ng-model="fields.three" name="thirdField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />
<br/>
<button type="submit" ng-disabled="!myForm.$valid">Submit</button>
</form>
有关详细信息,请参阅此工作小提琴示例.
See this working fiddle example for more details.
您可以通过阅读这个问题
You can have more details about required vs ng-required by reading this question
这篇关于表单验证 - 需要一组中的一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!