Justin Saraceno
Justin Saraceno

Reputation: 2526

Client validate non-model bound checkbox while using MVC 2 jQuery Validation

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!

Upvotes: 0

Views: 1642

Answers (3)

Sreejith-G
Sreejith-G

Reputation: 1

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;
        }
    });
});

Upvotes: 0

Vadim
Vadim

Reputation: 17965

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>

Upvotes: 1

Chase Florell
Chase Florell

Reputation: 47437

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.

Upvotes: 0

Related Questions