MVC 4 - DataAnnotations - Validation for Type

前端 未结 3 1940
傲寒
傲寒 2021-02-13 22:43

I have the following code working

    [Required(ErrorMessage = \"Price is required.\")]
    [Range(typeof(Decimal), \"1\", \"9999\", ErrorMessage = \"Price xx.xx         


        
3条回答
  •  盖世英雄少女心
    2021-02-13 23:14

    You can try with the regular expression:

    [RegularExpression(@"[0-9]*\.?[0-9]+", ErrorMessage = "{0} must be a Number.")]
    

    you can also try the Data Annotations Extensions: http://dataannotationsextensions.org/Home/Wiki

    Or write your own implementation,something like this : https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions/DigitsAttribute.cs

    UPDATE With REGEX (Matches $9,999.99 | $0.70 | .1)

    [RegularExpression(@"^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$", ErrorMessage = "{0} must be a Number.")]
    

    Or using Range with a slight modification to @Martin suggestion (actually is a better solution):

    [Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
    

提交回复
热议问题