验证单选按钮 AngularJS [英] Validate Radio Button AngularJS

查看:24
本文介绍了验证单选按钮 AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来应该相当简单,但我没有找到答案.我有一个表格,我需要在其中验证是否已从无线电组中进行选择.我尝试在单选按钮上使用 'required' 属性,但是当表单被验证时它会抱怨,除非选择了所有的单选按钮(这在设计上是不可能的).

This seems like it should be fairly easy, but I'm not finding the answer. I have a form where I need to validate that a selection has been made from a radio group. I tried using the 'required' attribute on the radio buttons, but when the form is validated it complains unless all the radio buttons are selected (which is impossible by design).

在 AngularJS 中验证单选组选择的正确方法是什么?

What is the proper way to validate a radio group selection in AngularJS?

<form name="myForm" ng-submit="submitForm()" ng-controller="ExampleController">
  <input type="radio" ng-model="color" value="red" required>  Red <br/>
  <input type="radio" ng-model="color" value="green" required> Green <br/>
  <input type="radio" ng-model="color" value="blue" required> Blue <br/>
  <tt>color = {{color | json}}</tt><br/>
  <button type="submit">Submit</button>
</form>

点击 Plnkr 中的提交按钮显示行为.

Clicking the submit button in the Plnkr shows the behavior.

http://plnkr.co/edit/3qcIbMvJk19OvokcHe2N?p=preview

推荐答案

尝试使用 ng-required="!color".这使得只有在未设置值时才需要该字段.如果设置了值,则删除 required 并通过验证.

Try using ng-required="!color". This makes it so that the field is only required when the value is not set. If a value is set, then required is removed and it will pass validation.

<input type="radio" ng-model="color" value="red" ng-required="!color">  Red <br/>
<input type="radio" ng-model="color" value="green" ng-required="!color"> Green <br/>
<input type="radio" ng-model="color" value="blue" ng-required="!color"> Blue <br/>

这是一个更新的 plunker,它表明表单现在可以正确验证:http://plnkr.co/edit/EdItU2IIkO1KIsC052Xx?p=preview

Here is an updated plunker that demonstrates that the form now validates correctly: http://plnkr.co/edit/EdItU2IIkO1KIsC052Xx?p=preview

e-cloud 的答案很简单,不需要额外的指令.如果可能,我建议每个人都使用这种方法.将这个答案留在这里,因为它确实提供了一个可行的解决方案并演示了 ng-required 指令的使用.

e-cloud's answer is simple and doesn't require an additional directive. I suggest everyone use that method if possible. Leaving this answer here as it does provide a working solution and demonstrates the use of the ng-required directive.

这篇关于验证单选按钮 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆