How to validate a decimal to be greater than zero using ValidationAttribute

7.8k Views Asked by At

I created a custom validator for an integer to check input greater than 0. It works fine.

Custom Validation for Integer

using System;
using System.ComponentModel.DataAnnotations;

public class GeaterThanInteger : ValidationAttribute
    {
        private readonly int _val;

        public GeaterThanInteger(int val)
        {
            _val = val;
        }   

        public override bool IsValid(object value)
        {
            if (value == null) return false;            
            return Convert.ToInt32(value) > _val;
        }       
    }

Calling code

[GeaterThanInteger(0)]
public int AccountNumber { get; set; }

Custom Validator for Decimal

I am trying to create similar validator for decimal to check input greater than 0. However I this time I ran in to compiler errors.

public class GreaterThanDecimal : ValidationAttribute
{
    private readonly decimal _val;

    public GreaterThanDecimal(decimal val)
    {
        _val = val;
    }

    public override bool IsValid(object value)
    {
        if (value == null) return false;
        return Convert.ToDecimal(value) > _val;
    }
}

Calling code

[GreaterThanDecimal(0)]
public decimal Amount { get; set; }

Compiler Error (points to the [GreaterThanDecimal(0)])

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

I tried few combinations,

[GreaterThanDecimal(0M)]
[GreaterThanDecimal((decimal)0)]

But does not work.

I looked through the ValidationAttribute definition and documentation, but I am still lost.

What is the error complaining about?

Is there any alternate way to validate Decimal greater than 0 in this case?

3

There are 3 best solutions below

4
HappyTown On BEST ANSWER

@JonathonChase answered it in the comments, I thought I would complete the answer with modified code sample here, in case someone stumbles upon this with the same problems.

What is the error complaining about?

Because the call [GreaterThanDecimal(0)] is trying to pass decimal as an attribute parameter, this is not supported by CLR. See use decimal values as attribute params in c#?

Solution

Change the parameter type to double or int

public class GreaterThanDecimalAttribute : ValidationAttribute
    {
        private readonly decimal _val;


        public GreaterThanDecimalAttribute(double val) // <== Changed parameter type from decimal to double
        {
            _val = (decimal)val;
        }

        public override bool IsValid(object value)
        {
            if (value == null) return false;
            return Convert.ToDecimal(value) > _val;
        }
    }
1
Tommix On

Use Range attribute. Also works great for decimals too.

[Range(0.01, 99999999)]
0
AliNajafZadeh On

Try following code:

[Range(1, int.MaxValue, ErrorMessage = "Value Must Bigger Than {1}")]