Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply a required field validation only if one radio button is selected

I'm using MVC Data Anottation for client validations.

How do you implement this simple scenario:

Mark a field as required only if one radio button is selected

like image 900
Erwin O. Avatar asked Sep 21 '25 10:09

Erwin O.


1 Answers

you wrote you're doing client side validation, so one way to accomplish your goal would be a simple javascript that would remove / modify validation rules attached to your input element:

$("#YourCheckBox").click(function(){ 
  if($(this).is(':checked')){
      $("#FirstName").rules("add","required")
  } else {
      $("#FirstName").rules("remove","required")
  }
});

you can find out more about validation plugin and its features here http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules

Of course you can easily find out more about jquery unobutrusive validation and do your variant. Thing to remember though is that you want to keep your client-side and backend validation consistent, so if you strip the [Required] from the model, you would have to check the value in your save/edit method.

like image 75
Paweł Staniec Avatar answered Sep 23 '25 11:09

Paweł Staniec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!