2014-09-04 109 views
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) 

回答

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

object value是你decimal值。如果值爲大於大於零,則它的值爲有效

+0

我的代碼id很好地工作,但是當它返回時返回新的ValidationResult(「Value can not be Zero」);那麼它也會被髮布到服務器.. – SantyEssac 2014-09-04 07:34:55

+0

我沒有得到我將不得不包括在視圖? – SantyEssac 2014-09-04 07:35:35

+0

我是否應該在視圖內包含一些東西? – SantyEssac 2014-09-04 07:49:52