gpt4 book ai didi

c# - ASP.NET MVC : Why Range Data Annotation is not working on checkbox in client side?

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:45 24 4
gpt4 key购买 nike

我有一个表单,其中一些字段带有 Required 数据注释,然后我有一个“接受条款和条件”复选框,带有数据注释 [Range(typeof(bool), "true", "true", ErrorMessage="您必须接受条款和条件才能继续")]一切正常,但令人讨厌的是 Required 数据注释在发布前触发错误。我的意思是,我点击提交,表单没有发布,但显示错误使用范围,表单发布,然后显示错误。

这是为什么呢?这是一种常见的行为吗?

最佳答案

我终于想到了这个解决方案:

public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
return (bool)value == true;
}

public override string FormatErrorMessage(string name)
{
return "The " + name + " field must be checked in order to continue.";
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
ValidationType = "enforcetrue"
};
}
}

在我的 JS 中:

jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
return element.checked;
});
jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");

关于c# - ASP.NET MVC : Why Range Data Annotation is not working on checkbox in client side?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com