0

假设我有一个实体属性,例如:

public decimal Amount { get; set; }

然后可以在元数据类中添加验证,例如:

[Range(0.01, double.MaxValue, ErrorMessage = "Amount is required")]
public decimal Amount { get; set; }

非零请求怎么样?

4

1 回答 1

2

您可以实现自定义验证属性。例子:

class MyObject {
    [NonZero]
    public decimal Amount { get; set; }
}

public class NonZeroAttribute : ValidationAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return string.Format("{0} must be non-zero", name);
    }

    public override bool IsValid(object value)
    {
        var zero = Convert.ChangeType(0, value.GetType());
        return !zero.Equals(value);
    }

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        if (IsValid(value))
            return new ValidationResult(null);
        else
            return new ValidationResult(
                FormatErrorMessage(validationContext.MemberName)
            );
    }
}
于 2013-04-25T20:08:23.280 回答