简体   繁体   English

AngularJS单选按钮验证

[英]AngularJS radio button validation

Simple and easy. 简单容易。

I got two radio buttons. 我有两个单选按钮。

<input type="radio" name="gender" ng-model="male">
<input type="radio" name="gender" ng-model="female">

How do i validate in AngularJS that at least one is chosen? 我如何在AngularJS中验证是否至少选择了一个? And how can i type something like 我该如何输入

$scope.myForm.gender.$invalid

Any ideas? 有任何想法吗?

use required : 需要使用:

   <input type="radio" name="gender" ng-model="male" required>
   <input type="radio" name="gender" ng-model="female" required>

DEMO 演示

same Question asked here : Validate Radio Button AngularJS 在这里问同样的问题: 验证单选按钮AngularJS

Without a form, you can fix this by check the value of the models in your controller, returning an error if both are false. 如果没有表单,则可以通过检查控制器中模型的值来解决此问题,如果两者都为假,则返回错误。 You could also go ahead and set one true by default. 您还可以继续进行设置,并默认设置为true。

But to answer your question, you can do something similar to $scope.myForm.gender.$invalid all you have to do is wrap your input tags in a form with the name myForm. 但是要回答您的问题,您可以执行类似于$scope.myForm.gender.$invalid ,只需将输入标签包装在名为myForm的表单中即可。 So, it would like: 因此,它想:

<form name="myForm">
   <input type="radio" name="gender" ng-model="male">
   <input type="radio" name="gender" ng-model="female">
</form>

Then, $scope.myForm would be able to give you certain properties, like $isPristine and properties for each input field. 然后, $scope.myForm将能够为您提供某些属性,例如$isPristine和每个输入字段的属性。

Either of these ways will work though, so I help that helps! 这些方法中的任何一种都可以,但是我可以帮助您!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM