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?