Search code examples
jqueryasp.net-mvc-3jquery-validateunobtrusive-validation

MVC3/4 Validating Hidden Fields


I have set up model validation for my form but validation doesn't seem to work at all. I don't suppose anybody can help. I've tried using the below work-around but that keeps pulling up an 'undefined' error in firebug.

Example Work-Around Script:

<script type="text/javascript">
    $(document).ready(function () {            
        $.validator.setDefaults({ ignore: [] });
    });
</script>

Example Text Field (Note: autocomplete text field with name of customer):

    @Html.TextBox("txtCustomer", null, new { @id = "txtCustomer", @class = "txt" })

Example Hidden Field (Note: When selection is made from the autocomplete field, the id is injected into the hidden field):

    @Html.HiddenFor(model => model.Customer_ID, new { @id = "hCustomerID" })

Example Model Data Annotation

    [Range(1, Int32.MaxValue, ErrorMessage = "Please select a customer")]
    public int Customer_ID { get; set; }

EDIT: Screenshot of errors

Sorry i have to post links to the screenshots because my rep points are high enough.

UI Postback Error

EDIT: Screenshot showing page source

Screenshot of Page Source


Solution

  • Its too late to change the ignore on the validator in this way after the unobtrusive script. This is because the validator only pulls in the defaults once - when it is created. The unobtrusive script creates the validator for you. You need to reference the existing validator object and update it.

    try this

    <script>
        $(document).ready(function () {            
            $('form').validate().settings.ignore = []
        });
    </script>