12

I am using ASP.NET MVC2 and trying to validate my view models using the attributes in System.ComponentModel.DataAnnotations namespace.

How can I dynamically set the permitted valid range of a RangeAttribute? For example, if I want to validate that a date entered is within an expected range.

This doesn't compile:

[Range(typeof(DateTime), 
        DateTime.Today.ToShortDateString(), 
        DateTime.Today.AddYears(1).ToShortDateString())]
    public DateTime DeliveryDate { get; set; }

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

Do I need to resort to creating my own custom validator?

2 Answers 2

15

OK, found the answer. .NET Framework 4 provides a new CustomValidationAttribute which makes the following possible:

[Required]
[DisplayName("Ideal Delivery Date")]
[CustomValidation(typeof(HeaderViewModel), "ValidateDeliveryDate")]
public DateTime DeliveryDate { get; set; }

public static ValidationResult ValidateDeliveryDate(DateTime deliveryDateToValidate)
{
    if (deliveryDateToValidate.Date < DateTime.Today)
    {
    return new ValidationResult("Delivery Date cannot be in the past.");
    }

    if (deliveryDateToValidate.Date > DateTime.Today.AddYears(1))
    {
    return new ValidationResult("Delivery Date must be within the next year.");
    }

    return ValidationResult.Success;
}

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28VS.100%29.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

Anyway to validate if I have two date type properties like start and end date and make sure that start is not after end using some scheme like this (custom validation class, attributes)?
0

You need to create your own attribute or use a none attribute based validation framework. As the message say, all parameters to any attribute needs to be constant values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.