Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  164] [ 7]  / answers: 1 / hits: 86022  / 10 Years ago, thu, july 10, 2014, 12:00:00

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).



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>


Clicking the submit button in the Plnkr shows the behavior.



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


More From » html

 Answers
8

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/>


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



Update



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.


[#70242] Wednesday, July 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
latrelllloydb

Total Points: 449
Total Questions: 92
Total Answers: 100

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;