Search code examples
c#.netvalidationc#-5.0custom-validators

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


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?


Solution

  • @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;
            }
        }