零值的自定义验证

时间:2014-09-04 07:01:20

标签: jquery asp.net-mvc-3

我想实现零或小于零的验证,即用户必须无法将值设置为0或小于0。 为此,我使用了以下代码:

public class PosNumberNoZeroAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            int getal;
            if (int.TryParse(value.ToString(), out getal))
            {

                if (getal == 0)
                    return new ValidationResult("Value can not be Zero");

                if (getal > 0)
                    return ValidationResult.Success;
            }
            return ValidationResult.Success;


        }
    }

[PosNumberNoZero(ErrorMessage = "need a positive number, bigger than 0")]
public decimal AmountReceivedByToAccount { get; set; }

查看:

@Html.TextBoxFor(m => m.AmountReceivedByToAccount, new { style = "max-width:144%;width:132%;" })
@Html.ValidationMessageFor(m => m.AmountReceivedByToAccount)

1 个答案:

答案 0 :(得分:0)

    public class PosNumberNoZeroAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return (decmial)value > 0;
        }
    }

object value是您的decimal值。如果值大于大于零,那么它有效