Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable validation for certain fields

Tags:

asp.net-mvc

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.

like image 527
ngruson Avatar asked Nov 20 '12 11:11

ngruson


2 Answers

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.

like image 59
ngruson Avatar answered Sep 22 '22 20:09

ngruson


<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>
like image 36
Owen Avatar answered Sep 19 '22 20:09

Owen