0

Have: Using ASP.NET MVC 2, DataAnnotationsModel based server validation, and client validation with jQuery. Anything in my model is validated perfectly on the client with jQuery based validation (jQuery.validate and MicrosoftMvcJQueryValidation.js).

Need: Adding an additional HTML <input type="checkbox" id="terms" /> to my form. I need jQuery validation to require that this checkbox is checked AND somehow hook it in with whatever jQuery client script MVC is automagically controlling. Yes, I know it won't validate on the server side, but I don't need or want it to.

Seems like it should be simple but I'm new to MVC, a total beginner at jQuery, and my searches have been coming up blank.

Any help would be appreciated!

3 Answers 3

1

Here's a solution. It mimics what mvc does to hook into jQuery validation. So there's a checkbox called Accept that doesn't belong to the model. The script must go after the form and it adds all the validation meta data for that field.

    <%
        Html.EnableClientValidation(); %>
    <% using(Html.BeginForm("Show"))
{ %>
      <%= Html.EditorForModel() %>
      <div class="editor-field">
        <%= Html.CheckBox("Accept", new { @class = "required" })%> 
        <span class="field-validation-valid" id="Accept_validationMessage"></span>
      </div>
      <input type="submit" value="Submit" />
<%} %>
<script type="text/javascript">
    window.mvcClientValidationMetadata[0].Fields.push({
        FieldName: "Accept",
        ReplaceValidationMessageContents: true,
        ValidationMessageId: "Accept_validationMessage",
        ValidationRules: [{ ErrorMessage: "The Accept field is required.", ValidationType: "required", ValidationParameters: {}}]
    });
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

This gets me closer but the validation for this checkbox seems to be competing with MVC's auto-wired jQuery validation event. What is happening is I see the client validation message for the new checkbox but then the validation messages for all the other fields disappear.
@Justin I've set up a test page that has an Html.EditorFor() statement and an extra checkbox with the class="required" and I don't see the competing messages. Perhaps you can post your aspx and JS code.
Would there be any JS code for this? Doesn't the jQuery.validate library use class="required" attribute of the checkbox to hook up a form submittal validation check?
0

Might I suggest using a ViewModel for every View (put all of your dataannotations in there). Then you can create a boolean model property for your checkbox and set it to required.

From there, if you're posting the model back to the controller, you can simply use AutoMapper to map the ViewModel to the needed model, or simply map the properties yourself.

Either way, it is good practice to use a ViewModel for every view. Remember a ViewModel's job is to try and contain everything required in the view. This definitely means that it can and will have other data that is not required in the Model.

3 Comments

I was hoping to avoid all this because I'd also have to create a custom validator class, register it in global.asax, bla, bla.... too much work for one little checkbox whose value I didn't need to store anyway. But I see no way around it and this is what I had to do. Thanks.
If you're willing to upgrade to MVC 3, you can build a validator controller instead of a custom validator. Then you can use remote validation for your client side stuff.
That would be ideal but I'm stuck on a .NET 3.5 platform. However, it turns out I didn't need a custom validator. I assumed I would because I thought jQuery would just evaluate the text value (true or false) and see it was not an empty string, therefore fulfilling the DataAnnotation 'Required' requirement. I was wrong. Using [Required(ErrorMessage = "Checkbox must be checked")] actually worked and was evaluated correctly by jQuery; no custom validator needed
0

Try this

$(document).ready(function() {
    //// Assuming your form's ID is 'form0'
    $("#form0").submit(function() {  
        if ($("#terms").attr('checked')) {
            return true;
        }
        else
        {
           //// Error message if any
           return false;
        }
    });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.