dresscode
dresscode

Reputation: 13

Trouble with checkbox validation in Razor form

I am currently at an internship and am completely new to Razor and C# MVC. I am currently building a simple Razor form, but my validation is giving me grief for a check box.

Here is my model code:

[DisplayName("Sign me up for spam* ")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You must sign up for spam.")]
public bool Check { get; set; }

Here is my Razor markup:

@Html.LabelFor(model => model.Check, new { @class = "" })
@Html.CheckBoxFor(model => model.Check, new { @class = "example1"})

Here is the generated HTML:

<input class="example1" data-val="true" data-val-range="You must sign up for spam." data-val-range-max="True" data-val-range-min="True" data-val-required="The Sign me up for spam*  field is required." id="Check" name="Check" type="checkbox" value="true">
<input name="Check" type="hidden" value="false">

I know that Razor will generate both inputs automatically. My problem is that the validation is simply not working on the check box. The model state is always invalid because of it, and on the client side the error message appears when the box is checked and disappears when the box is unchecked. I have been googling for answers, but have come up short and my mentor doesn't know what is going screwy either.

Upvotes: 1

Views: 3620

Answers (1)

Pankwood
Pankwood

Reputation: 1878

It looks like a client side reversed issue. Add this jquery in your page and I think it will be fixed:

<script>
    // extend range validator method to treat checkboxes differently
    var defaultRangeValidator = $.validator.methods.range;
    $.validator.methods.range = function(value, element, param) {
        if(element.type === 'checkbox') {
            // if it's a checkbox return true if it is checked
            return element.checked;
        } else {
            // otherwise run the default validation function
            return defaultRangeValidator.call(this, value, element, param);
        }
    }
</script>

Upvotes: 3

Related Questions