1

自定义属性

public class BooleanMustBeTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object propertyValue)
    {
         return propertyValue != null
             && propertyValue is bool
             && (bool)propertyValue;
     }
}

模型

[MetadataType(typeof(ProductMeta))]
public partial class Product
{
   public virtual bool ItemOwner { get; set; }
}

public class ProductMeta
{
[Required]
[BooleanMustBeTrue(ErrorMessage = "Please tick")]
public virtual bool ItemOwner { get; set; }
}

看法

@Html.CheckBoxFor(m=>m.ItemOwner)
@Html.ValidationMessageFor(m=>m.ItemOwner)

我的代码中上面的所有内容看起来都正确,但复选框验证仍然不起作用。以上验证甚至不适用于控件。

我的应用程序在 MVC4 中。

请指教。

4

3 回答 3

1

试试下面的代码

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"
        };
    }
}

然后将以下代码添加到您的 javascript 文件中。

jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
    return element.checked;
});
jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");
于 2014-05-08T10:30:03.593 回答
1

您可以从这个答案中得到一些想法:How to handle Booleans/CheckBoxes ...。特别是来自 43 票赞成的答案。

很可能您的解决方案就在这里:逻辑:使用 CheckBoxFor 和代码示例检查所需的复选框: MVC 模型需要 true,这与第一个答案没有太大区别。如果为其他人工作,也必须为你工作。

希望这会有所帮助。

于 2013-06-04T12:56:36.497 回答
0

这个怎么样?

   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;
        }
于 2013-05-31T05:12:09.140 回答