custom rangeValidation

1

How to make a range validator where Max is the current year + 1?

I'm trying to do a dataannotation validation on my models I want to make a range validation from 1950 until current year +1 By default it is not possible to do this using the default range

 [Range(1950, Convert.ToDouble(DateTime.Now.Year+1), ErrorMessage = "O ano deve estar entre {1} e {2}!" )]

You can not enter a variable in the value. So I tried to expand the RangeAttribute class.

public class StringLengthRangeAttribute : ValidationAttribute
{
                public int Min { get; set; }
                public int Max { get; set; }

                public StringLengthRangeAttribute()
                {
                    this.Min = 0;
                    this.Max = DateTime.Now.Year + 1;
                }

                public override bool IsValid(object value)
                {
                    string strValue = value as string;
                    if (!string.IsNullOrEmpty(strValue))
                    {
                        int len = strValue.Length;
                        return len >= this.Min && len <= this.Max;
                    }
                    return true;

                }
}

But on the client side it did not validate !. I tried with the example described here, and it also did not work. link

    
asked by anonymous 25.08.2017 / 15:07

1 answer

1

On this line:

int len = strValue.Length;

You are getting the amount of characters that are part of this string and not its value, so your return does something like:

return 4 >= 0 && 4 <= 2018;

Since 2017, for example, has 4 characters. Try something like:

if (value is int)
{
    return value >= this.Min && value <= this.Max;
}

Getting the final code:

public class StringLengthRangeAttribute : ValidationAttribute
{
    public int Min { get; set; }
    public int Max { get; set; }

    public StringLengthRangeAttribute()
    {
        this.Min = 0;
        this.Max = DateTime.Now.Year + 1;
    }

    public override bool IsValid(object value)
    {
        try
        {
            int strValue = Convert.ToInt32(value);
            return strValue >= this.Min && strValue <= this.Max;
        }
        catch (Exception)
        {
            Console.WriteLine("Formato inválido");
        }
    }
}
    
25.08.2017 / 16:01