Search code examples
asp.net-mvcvalidationmodel-validationfoolproof-validation

Conditional Validation ie. Requiring a field only if a certain radio button is checked?


This is more of a pointing in the right direction sort of thing. I'm currently working on a project where a handful of fields will be hidden until a radio button is checked, therefore also not required until then. So tick the specific radio button, fields show up and they are now required on submit with the [Required] DataAnnotations attribute in the model.

I went down the path of trying to use MVC Foolproof and [RequiredIf], but didn't have much luck considering the outdated js files necessary and was wondering if someone else had a simpler solution.

I appreciate any input. I feel like this isn't too uncommon of a task but had a lot of difficulty finding a solution via Google.


Solution

  • I am sure you can accomplish this with using Javascript/Jquery.

    Like so:

    if($('#idNameOfRadioBtn').is(':checked')){
        $('#idOfFieldNameThatIsNowRequired').attr('required');
    }
    else{
        $('#idOfFieldNameThatIsNowRequired').removeAttr('required');
    }
    

    Let me know if this helps!