数据注释不适用于复选框

时间:2013-04-19 11:02:54

标签: asp.net-mvc validation asp.net-mvc-4 data-annotations

自定义属性

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。

请告知。

3 个答案:

答案 0 :(得分:1)

您可以从这个答案中获得一些想法:How to handle Booleans/CheckBoxes ...。特别是从43票上来回答。

很可能你的解决方案就在这里:逻辑:Required checkbox to be checked using CheckBoxFor 代码示例:MVC Model require true,与第一个答案没有太大区别。如果为其他人工作,也必须为你工作。

希望这有用。

答案 1 :(得分: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");

答案 2 :(得分: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;
        }
相关问题