23

我正在尝试实现本文中提到的代码。换句话说,我正在尝试在条款和条件复选框上实施不显眼的验证。如果用户没有选择复选框,那么输入应该被标记为无效。

这是服务器端验证器代码,我已添加:

/// <summary>
/// Validation attribute that demands that a boolean value must be true.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && value is bool && (bool)value;
    }
}

这是模型

[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
[DisplayName("Accept terms and conditions")]
public bool AcceptsTerms { get; set; }

这是我的看法:

@Html.EditorFor(x => x.AcceptTermsAndConditions)
@Html.LabelFor(x => x.AcceptTermsAndConditions)
@Html.ValidationMessageFor(x => x.AcceptTermsAndConditions)

这是我用来附加验证器客户端的 jQuery:

$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");

但是,客户端脚本似乎没有启动。每当我按下提交按钮时,其他字段的验证都会正常启动,但条款和条件的验证似乎没有启动。这就是我单击提交按钮后代码在 Firebug 中的样子。

<input type="checkbox" value="true" name="AcceptTermsAndConditions" id="AcceptTermsAndConditions" data-val-required="The I confirm that I am authorised to join this website and I accept the terms and conditions field is required." data-val="true" class="check-box">
<input type="hidden" value="false" name="AcceptTermsAndConditions">
<label for="AcceptTermsAndConditions">I confirm that I am authorised to join this website and I accept the terms and conditions</label>
<span data-valmsg-replace="true" data-valmsg-for="AcceptTermsAndConditions" class="field-validation-valid"></span>

有任何想法吗?我错过了一步吗?这让我如厕!

在此先感谢

4

6 回答 6

37

您需要在自定义属性上实现IClientValidatablemustbetrue以便将您在客户端注册的适配器名称与此属性绑定:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return value != null && value is bool && (bool)value;
    }

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

更新:

完整的工作示例。

模型:

public class MyViewModel
{
    [MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
    [DisplayName("Accept terms and conditions")]
    public bool AcceptsTerms { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

看法:

@model MyViewModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
    $.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
</script>

@using (Html.BeginForm())
{
    @Html.CheckBoxFor(x => x.AcceptsTerms)
    @Html.LabelFor(x => x.AcceptsTerms)
    @Html.ValidationMessageFor(x => x.AcceptsTerms)
    <input type="submit" value="OK" />
}
于 2011-08-03T10:15:10.817 回答
26

嗅探器,

除了实现达林的方案外,还需要修改文件jquery.validate.unobtrusive.js. 在这个文件中,你必须添加一个“mustbetrue”验证方法,如下:

$jQval.addMethod("mustbetrue", function (value, element, param) {
    // check if dependency is met
    if (!this.depend(param, element))
        return "dependency-mismatch";
    return element.checked;
});

然后(我一开始忘了添加这个),您还必须将以下内容添加到jquery.validate.unobtrusive.js

adapters.add("mustbetrue", function (options) {
    setValidationValues(options, "mustbetrue", true);
});

辅导员本

于 2011-08-03T18:38:39.610 回答
5

我不确定为什么这对我不起作用,但我选择使用您的代码并做一些稍微不同的事情。

在我的 JavaScript 加载中,我添加了以下内容,如果您选择复选框并取消选中它,这会使复选框触发不显眼的验证。另外,如果您提交表格。

$(function () {
        $(".checkboxonblurenabled").change(function () {
            $('form').validate().element(this);
        });
});

您还需要将 CSS 类添加到您的复选框,就像这样。

@Html.CheckBoxFor(model => model.AgreeToPrivacyPolicy, new { @class = "checkboxonblurenabled"})

所以,我们现在需要连接模型并放入类来处理服务器端验证(我从上面重复使用),但稍微改变不显眼。

这是扩展 IClientValidate 的客户属性,如上例所示...

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return value != null && value is bool && (bool)value;
    }

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

在您的模型中,对象属性设置所需的属性符号

 [MustBeTrue(ErrorMessage = "Confirm you have read and agree to our privacy policy")]
    [Display(Name = "Privacy policy")]
    public bool AgreeToPrivacyPolicy { get; set; }

好的,我们已经准备好放入 JavaScript。

(function ($) {
    /*
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
    */
    jQuery.validator.unobtrusive.adapters.add("mustbetrue", ['maxint'], function (options) {
        options.rules["mustbetrue"] = options.params;
        options.messages["mustbetrue"] = options.message;
    });

    jQuery.validator.addMethod("mustbetrue", function (value, element, params) {

        if ($(element).is(':checked')) {
            return true;
        }
        else {
            return false;
        }
    });
    /*
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
    */



} (jQuery));

是什么让这项工作,是......好吧。在尝试执行上述建议的答案后查看 HTML 标记后,我的值都设置为 true,但是我选中的复选框为 false。所以,我决定让 jQuery 使用 IsChecked 来解决它

于 2012-04-24T15:33:21.090 回答
2

对于那些这些解决方案都不起作用的人:

我正在使用 .Net Framework 4 使用 Razor MVC 4,以及最新的 jquery 验证脚本文件。

在客户端和服务器端实现自定义属性验证后,它仍然不起作用。无论如何,我的表格正在发布。

所以这里有一个问题:JQuery 验证脚本有一个默认设置忽略隐藏标签,其中 hidden 是http://api.jquery.com/hidden-selector/,这通常不会成为问题,但 @Html.CheckBoxFor 风格我正在使用的自定义 CSS3 样式将显示更改为无,并显示复选框的自定义图像,因此它永远不会在复选框上执行验证规则。

我的解决方法是在自定义客户端验证规则声明之前添加此行:

$.validator.defaults.ignore = "";

它所做的是覆盖当前页面中所有验证的忽略设置,注意现在它也可以在隐藏字段上执行验证(副作用)。

于 2013-12-17T18:03:52.390 回答
1
<script>
    $(function () {
        $('#btnconfirm').click(function () {
            if ($("#chk").attr('checked') !== undefined ){
                return true;
            }
            else {

                alert("Please Select Checkbox ");
                return false;
            }
        });

    });
</script>
<div style="float: left">
                    <input type="checkbox" name="chk" id="chk"  />
                    I read and accept the terms and Conditions of registration
                </div>
  <input type="submit" value="Confirm"  id="btnconfirm" />
于 2014-02-26T11:19:44.720 回答
0
/// <summary> 
///  Summary : -CheckBox for or input type check required validation is not working the root cause and solution as follows
///
///  Problem :
///  The key to this problem lies in interpretation of jQuery validation 'required' rule. I digged a little and find a specific code inside a jquery.validate.unobtrusive.js file:
///  adapters.add("required", function (options) {
///  if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
///    setValidationValues(options, "required", true);
///    }
///   });
///   
///  Fix: (Jquery script fix at page level added in to check box required area)
///  jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {
///   if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
///              options.rules["required"] = true;
///   if (options.message) {
///                   options.messages["required"] = options.message;
///                       }
///  Fix : (C# Code for MVC validation)
///  You can see it inherits from common RequiredAttribute. Moreover it implements IClientValidateable. This is to make assure that rule will be propagated to client side (jQuery validation) as well.
///  
///  Annotation example :
///   [BooleanRequired]
///   public bool iAgree { get; set' }
///    

/// </summary>


public class BooleanRequired : RequiredAttribute, IClientValidatable
{

    public BooleanRequired()
    {
    }

    public override bool IsValid(object value)
    {
        return value != null && (bool)value == true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "brequired", ErrorMessage = this.ErrorMessage } };
    }
}
于 2014-12-31T09:33:51.850 回答