custom rangeValidation

Asked

Viewed 45 times

1

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

I’m wanting to do a validation in dataannotation on my models I want to do a validation range from 1950 to current year +1 By default it is not possible to do using the default range

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

cannot insert a variable into 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 he did not do the validation!. tried with the example described here, and also did not work. https://stackoverflow.com/questions/7843334/data-annotations-how-can-i-replace-range-values-with-web-config-values-in-mvc3?lq=1

1 answer

1


Along those lines:

int len = strValue.Length;

You’re picking up the amount of characters that are part of that 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;
}

Thus remaining 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");
        }
    }
}
  • 1

    I edited your answer with the final code, see if this was it? but it worked.. thanks

  • now the clause SE will always be true since if I fail to make the conversion will burst an untreated exception, but solve the case yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.