Reputation: 1965
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.
Upvotes: 1
Views: 1389
Reputation: 2753
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>
Upvotes: 2
Reputation: 5953
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!
Upvotes: 2