views:

71

answers:

2

Hi all,

Can't seem to get checkbox to be validate on client-side using asp.net mvc 2. Here is my code.

Model

[Serializable]
public class RegistrationModel
{
    bool termsAndCondition = false;
    [RequiredToBeTrue(ErrorMessage = "Need terms and service")]
    public bool TermsAndConditions
    {
        get
        {
            return termsAndCondition;
        }
        set
        {
            termsAndCondition = value;
        }
    }
}

Custom Attribute

public class RequiredToBeTrueAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        return (value != null) && (value is bool) ? (bool)value : false;
    }
}

View

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<RegistrationModel>" %>

 <% Html.EnableClientValidation(); %>
 <% using (Html.BeginForm("Register", "Registration", new { area="Account", id = "openid_form", inRegistration = true }))
 <%=Html.ValidationSummary(false)  %>
 blah blah blah
 <div class="checkbox"><label><%= Html.CheckBoxFor(model => model.TermsAndConditions) %>I agree to the <a href="content/terms-conditions.html" id="terms-contents">terms and conditions</a> of use.</label></div>
 <input type="submit" id="submit" name="submit" value="Join Now" />
 <%
    Html.ValidateFor(m => m.TermsAndConditions);            
 %>
 <% } %>      

I am trying to call Html.ValidateFor at the end to push up all error message at top of the page. However, the property "TermsAndConditions" is not getting validated on client side (works great on server side). This leads me to look at the the window.mvcClientValidationMetData method at that mvc push out and I saw the following:

{"FieldName":"TermsAndConditions","ReplaceValidationMessageContents":false,"ValidationMessageId":null,"ValidationRules":[]}

Which you can see that "ValidationRules" are empty meaning that it is trying to validate it but the error message wasn't push out to the client for some reason.

Any ideas? Any help is appreciated.

A: 

Seems like I need to do more digging first. Was hoping the new attribute will appear magically on the client side. Instead, have to write some customer javascript to wire it up. See phil hack's post for detail.

Herman
A: 

This article from Phil Haack, ASP.NET MVC 2 Custom Validation, should help point you in the right direction.

Basically you need to create your own DataAnnotationsModelValidator<RequiredToBeTrueAttribute> and then write some client side script to get it done.

HTHs,
Charles

Charlino