views:

20

answers:

1

I am using DataAnnotations tags for client-side validation in ASP.NET MVC2. I am using the Required tag, but in my case marking a field as required is not always an absolute. I have other conditions that determine whether or not a field is required.

Is it possible to override the required tag to allow for this conditional logic?

I would like to do something like this:

public class ConditionalRequiredAttribute : RequiredAttribute
{
    public ConditionalRequiredAttribute(string someParameter)
    {
        //Logic to determine if this field is required.
    }
}

And then use this attribute like this:

[ConditionalRequired("some parameter info")]
public virtual string EMailAddress { get; set; }

Any suggestions on how to make this work for client-side validation?

Thanks!

A: 

I'd recommend not using [Required] for this, as [Required] and subclassed types have the special meaning of being always required - not conditionally required.

You can make your own attribute which subclasses ValidationAttribute and carries along client-side validation info. There are several resources available for how to write custom client-side validation code. For example, see:

In MVC 3, you can use IClientValidatable for this, which makes life a little simpler. See http://blogs.msdn.com/b/stuartleeks/archive/2010/07/28/asp-net-mvc-adding-client-side-validation-to-validatepasswordlengthattribute-in-asp-net-mvc-3-preview-1.aspx for an example.

Levi