码迷,mamicode.com
首页 > Web开发 > 详细

在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)

时间:2016-11-21 08:47:02      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:present   nbsp   splay   set   public   ext   term   des   ast   

转载自 http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/

Why would you want to have a required checkbox, i.e. a checkbox that user would have to check? Well, a typical example would be that you have some sort of terms associated with submitting a form that the user has to agree to.

You might think that decorating a boolean property on one of your MVC models with a RequiredAttribute, would mean that if you presented that property in your view as a checkbox, that would require the user to click that checkbox before submitting the form. This is not the case however. If you take a look at the implementation of the RequiredAttribute it is actually casting the value to validate into a string and checking the string length. If it can’t cast the value to a string, it will just return true for IsValid.

It is quite easy however to create your own custom validation attribute that you could decorate your boolean property with. The following code checks if the decorated property is a bool, and if so, requires it to have been set to true;

public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value is bool)
            return (bool)value;
        else
            return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata,
        ControllerContext context)
    {
        yield return new ModelClientValidationRule
                            {
                                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                                ValidationType = "booleanrequired"
                            };
    }
}

Notice the GetClientValidationRules-method above where we specify the error message to display if client-side validation fails, and what the validation type is. The value we provide as the validation type will be rendered as the name of the rule in the HTML element, and will be used further down to tell jQuery how to validate this property.

After creating the new validation attribute, we need to apply it to a boolean property on out model;

[BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
[Display(Name = "I accept the terms and conditions")]
public bool TermsAndConditionsAccepted { get; set; }

Next, create a simple view with a form that includes you boolean property;

@model MyModel@using (Html.BeginForm())
{
    <fieldset>
        <legend>Terms and Conditions</legend>
        @Html.ValidationSummary(true, "Please correct the errors and try again.")
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Fusce facilisis ullamcorper consequat. Vestibulum non sapien lectus.
            Nullam at quam eu sapien mattis ultrices.
        </p>
        <ol>
            <li>
                @Html.CheckBoxFor(m => m.TermsAndConditionsAccepted)
                @Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @class = "checkbox" })
                @Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted)
            </li>
        </ol>
        <input type="submit" value="Submit" />
    </fieldset>
}

Lastly, in order for client-side validation to work, you need to include the following script in your view (or you can just put line 3 in a javascript file that you reference);

<script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
    } (jQuery));
</script>

This just registers a new validation adapter for the boolean required attribute, where the first parameter is the adapter name and the second parameter is the name of jQuery validate rule. The adapter name should match the value we specified earlier as the validation type, and the jQuery validation required-rule will require the user to check the checkbox.

That’s it! This will make sure that the checkbox is checked by the user client-side (using jQuery unobtrusive validation*) and that the boolean property is set to true server-side when the form is submitted to the server.

*The ClientValidationEnabled and UnobtrusiveJavaScriptEnabled application settings must be set to true in your web.config for client-side validation to work.

 

在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)

标签:present   nbsp   splay   set   public   ext   term   des   ast   

原文地址:http://www.cnblogs.com/wphl-27/p/6084178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!