Search code examples
asp.netasp.net-mvcasp.net-mvc-validation

mvc stop clientside validation on a certain field?


I have the following property in my model:

    [DisplayName("Pay to RE Date")]
    public DateTime? PaymentToRE { get; set; }

Whenever I type in something that is not a valid date, I get the message:

The value 'asdas' is not valid for Pay to RE Date.

I however, did not want validation happening at this point, as I have other properties which I need to validate and want all to validate together. The others require me to look up information in the database, so I did not want client side validation on this field. Is there anyway to disable it?

This is used in my view as below:

            @Html.LabelFor(model => model.PaymentToRE, new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @{Html.EnableClientValidation(false);}
                @Html.TextBoxFor(model => model.PaymentToRE, "{0:MM/dd/yyyy}", new { @class = "datepicker-input form-control" })
                @{Html.EnableClientValidation(true);}
                @Html.ValidationMessageFor(model => model.PaymentToRE)
            </div>

I tried using the Html.EnableClientValidation method, but that doesn't seem to stop it. And I didn't want to disable ClientValidation for the entire application as I need it on other forms.


Solution

  • I guess you are using jQuery validation plugin. You can use its option ignore. http://jqueryvalidation.org/validate/#ignore

    Add a ignore class to you textbox:

    @Html.TextBoxFor(model => model.PaymentToRE, "{0:MM/dd/yyyy}", new { @class = "datepicker-input form-control no-client-validation" })
    

    And add to jQuery validation option ignore the new class no-client-validation:

    $.validator.setDefaults({
        ignore: '.no-client-validation, :hidden' //:hidden is default value
    });
    

    EDIT

    Or you switch to remote validation, might be overhead in your case.

    http://msdn.microsoft.com/en-us/library/gg508808%28vs.98%29.aspx