Validate decimal value to 2 decimal places with data annotations?

前端 未结 8 1353
青春惊慌失措
青春惊慌失措 2020-12-03 07:20

I have this in my view model:

[Required(ErrorMessage = \"Price is required\")]
[Range(0.01, 999999999, ErrorMessage = \"Price must be greater than 0.00\")]
[         


        
相关标签:
8条回答
  • 2020-12-03 08:10

    I had the same scenario as the OP, yet the answers provided don't give a solution that works for all of the following cases:

    12, 12.3 and 12.34

    To do that, we use the following regular expression:

    [RegularExpression(@"^\d+(.\d{1,2})?$")]
    
    0 讨论(0)
  • 2020-12-03 08:14

    You can also create your own Decimal validation attribute, inheriting from RegularExpressionAttribute:

     public class DecimalAttribute : RegularExpressionAttribute
     {
        public int DecimalPlaces { get; set; }
        public DecimalAttribute(int decimalPlaces)
            : base(string.Format(@"^\d*\.?\d{{0,{0}}}$", decimalPlaces))
        {
            DecimalPlaces = decimalPlaces;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format("This number can have maximum {0} decimal places", DecimalPlaces);
        }
     }
    

    and register it to enable client-side validation in Application_Start():

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DecimalAttribute), typeof(RegularExpressionAttributeAdapter));
    
    0 讨论(0)
提交回复
热议问题