开发者

How to create comparison validator MVC2

开发者 https://www.devze.com 2023-01-15 10:01 出处:网络
i have 2 properties int开发者_开发百科 MinValue int MaxValue I have tocreate a data annotation attribute to validate this

i have 2 properties int开发者_开发百科 MinValue int MaxValue I have to create a data annotation attribute to validate this it should say 1)"MinValue should be less than MaxValue" if MinValue and MaxValue are not zero. 2)it should not compare the two values if both MinValue and MaxValue are zero(0).

any input from you to achieve this will help me sure in doing this


You could write a custom validator attribute deriving from ValidationAttribute

[AttributeUsage(AttributeTargets.Class)]
public class CustomValidateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = (MyModel)value;
        return model.MinValue < model.MaxValue;
    }
}

And decorate your model with this custom attribute:

[CustomValidate]
public class MyModel
{
    public decimal MinValue { get; set; }
    public decimal MaxValue { get; set; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消