w0051977
w0051977

Reputation: 15817

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?

Upvotes: 0

Views: 1156

Answers (1)

pisi1001
pisi1001

Reputation: 89

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)

Upvotes: 1

Related Questions