2017-08-25 19 views
0

我想要一個字段允許在正數上。我想下面的嘗試:如何在asp.net mvc中只允許在editorforfield中輸入正數5

型號

[Required] 
[GreaterThanZero(ErrorMessage = "Only positive number allowed.")] 
public int PositiveNumber { get; set; } 

查看

<div class="form-group"> 
      @Html.LabelFor(model => model.PositiveNumber, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(m => m.PositiveNumber) 
       @Html.ValidationMessageFor(model => model.PositiveNumber, "*", new { @class = "text-danger" }) 
      </div> 
     </div> 

自定義驗證

public class GreaterThanZero : ValidationAttribute 
    { 
     public override bool IsValid(object value) 
     { 
      var x = (int)value; 
      return x > 0; 
     } 
    } 

問題:上述方案正常工作。我想知道是否有任何簡單的方法來實現它。通過只使用一些內置的框架註釋/幫手甚至FoolProof

請注意:使用editorfor幫助只允許數字(它很聰明),但如果只是正數。

+0

您是否試過正則表達式驗證器 – PedroSouki

回答

2

這隻接受正數。

System.ComponentModel.DataAnnotations 
[Range(1, int.MaxValue, ErrorMessage = "Only positive number allowed")] 
相關問題