1

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
justiceorjustus
  • 2,017
  • 1
  • 19
  • 42
  • A foolproof `RequiredIf` works fine (and its not outdated). What problems were you having. The javascript solution in the accepted answer is just a poor hack and means you will have issues with server side validation. –  Aug 30 '16 at 02:53

2 Answers2

2

I suggest that you use angularjs for this as it is built for it. If you are not familiar with angular validation, here is a great article in scotch where it gives a really good demonstration. Good luck!

Hide and show fields based on ng-if directive and make field required using the required attribute. That's it!

<input type="text" 
       name="name" 
       class="form-control" 
       ng-model="user.name" 
       ng-if="user.required" 
       required>

Angular Validation

aholtry
  • 2,723
  • 3
  • 24
  • 26
2

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!

Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • So would I have the standard required fields validated in the model and the dynamic required fields from the radio button tick done in jquery? Separately? – justiceorjustus Aug 29 '16 at 15:34
  • @justiceorjustus it should work that way.. first the jquery will check the required fields, and if it passes then it will go to your controller and then it will go through that validation. – Grizzly Aug 29 '16 at 15:40
  • @justiceorjustus was this able to help? – Grizzly Aug 29 '16 at 17:59
  • 1
    This answer completely omits server-side validation. Client-side validation can always be circumvented. – michalstanko Nov 24 '17 at 10:54