开发者

How to override DataAnnotations Required tag to allow conditional client side validation

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开发者_JAVA百科 how to make this work for client-side validation?

Thanks!


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:

  • https://blogs.msdn.microsoft.com/stuartleeks/2010/07/27/asp-net-mvc-adding-client-side-validation-to-validatepasswordlengthattribute/
  • https://devermind.wordpress.com/2009/06/21/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜