简体   繁体   中英

Validate a decimal value

I was hoping to be able to do something like this:

 public class MinimumSalaryAttribute : ValidationAttribute
    {
        private readonly decimal _minValue;

        public MinimumSalaryAttribute(decimal minValue)
        {
            _minValue = minValue;
        }

        public override bool IsValid(object value)
        {
            return (decimal)value > _minValue;
        }
    }

and then in my view:

[MinimumSalary(0M)]
public decimal Salary { get; set; }

This would prevent users entering negative decimals. However, I get a compiler error: "not a valid attribute type". I understand the reason for this as described here: Why "decimal" is not a valid attribute parameter type?

What is the workaround in my vase?

You can use "Range" annotation; 10.50D is min value,50.80D is max value...

[Range(10.50D,50.80D,ErrorMessage ="Error min")]
public decimal Salary { get; set; }

Range attribute specifies the numeric range constraints for the value of a data field. It comes with System.ComponentModel.DataAnnotations (in System.ComponentModel.DataAnnotations.dll)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM