In my Razor view (ASP.NET MVC 4), I have two radiobuttons for showing/hiding some fields. When the first radiobutton is selected, these fields are invisible; when the second radiobutton is selected, the fields become visible. This is done by a Javascript function which is bound to the radiobuttons onclick event.
function displayHiddenFields(value) {
if (value == 'true')
$('#myDiv').removeClass('hidden');
else
$('#myDiv').addClass('hidden');
}
I'm using data annotations on the view model to perform validation. My problem is that the invisible fields are also validated. These fields only have to be validated when they are visible. I tried to manipulate the data-val attribute on the input elements but this doesn't work.
$('input1').attr('data-val', value);
How can I solve my problem? Is there a way to disable validation for the fields that are invisible by using client-side Javascript? Otherwise, I have to do a postback in order to render the fields conditionally.
I solved it by adding the following piece of JavaScript to the bottom of my page:
<script type="text/javascript">
$(function () {
var settings = $.data($('form').get(0), 'validator').settings;
settings.ignore = ".hidden";
});
</script>
This way, all the inputs that have the .hidden class applied to it will be ignored in the client-side validation.
<button id="Submit" type="submit">Submit</button>
<script type="text/javascript">
$("#Submit").on("click", function () {
var validator = $("form").data('validator');
validator.settings.ignore = "input[type=hidden]";
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With