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

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

问题描述

这似乎应该是相当容易的,但我没有找到答案。我有一个表格,我需要验证的选择已经从单选按钮组进行。我试着用收音机按钮必要的属性,但是当表单验证它抱怨,除非选择全部单选按钮(它的设计是不可能的)。

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.

<一个href=\"http://plnkr.co/edit/3qcIbMvJk19OvokcHe2N?p=$p$pview\">http://plnkr.co/edit/3qcIbMvJk19OvokcHe2N?p=$p$pview

推荐答案

尝试使用 NG-需要=!色。这使得它,以便当未设置的值字段时,才需要。如果设置一个值,然后再根据需要被删除,它会通过验证。

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演示表单验证现在正确:
<一href=\"http://plnkr.co/edit/EdItU2IIkO1KIsC052Xx?p=$p$pview\">http://plnkr.co/edit/EdItU2IIkO1KIsC052Xx?p=$p$pview

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

SaintScott的答案很简单,并且不需要额外的指令。我建议如果可能的话每个人都使用该方法。离开这里这个答案,因为它确实提供了一个可行的解决方案,并演示了如何使用NG-所需的指令。

SaintScott'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天全站免登陆