zoukankan      html  css  js  c++  java
  • 在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)

    转载自 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.

  • 相关阅读:
    [日常] 使用TCPDUMP和Ethereal抓包分析HTTP请求中的异常情况
    [视频教程] 基于redis的消息队列实现与思考
    [日常] 项目中业务绑定手机验证手机号的实现
    [视频教程] 使用docker的方式安装redis
    [前端] js中call方法的理解和思考
    [日常] Redis中set集合的使用思考
    [日常] 跨语言的POST请求问题的解决
    [PHP] 基于redis的分布式锁防止高并发重复请求
    [日常] 安装windows+deepin双系统
    [视频教程]利用SSH隧道进行远程腾讯云服务器项目xdebug调试
  • 原文地址:https://www.cnblogs.com/wphl-27/p/6084178.html
Copyright © 2011-2022 走看看