Search code examples
c#asp.net-mvc-3jquery-validatedata-annotations

Custom Validation Attribute Multiple Times on same field


How can I use Same Custom Validation Attribute Multiple Times on Same Field or simply enable AllowMultiple=true, for both server side and client side validation??

I have a following Custom Validation Attribute:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, 
        AllowMultiple = true, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute,IClientValidatable
{
    public RequiredIfAttribute(string dependentProperties, 
     string dependentValues = "",
     string requiredValue = "val")
     {
     }
}

Where in dependentProperties I can specify multiple dependant properties seperated by comma, in dependentValues I can specify for which values of dependant properties validation should process and finally in requiredValue I can specify expected value for the field to be validated.

In my model there are two properties LandMark, PinCode and I want to use validation as follows:

public string LandMark { get; set; }
[RequiredIf("LandMark","XYZ","500500")]
[RequiredIf("LandMark", "ABC", "500505")]
public string PinCode { get; set; }

The values here are just for example, as per it seems I can add the attribute multiple times and don't get any compile error, I have implemented TypeID in attribute and it works well from serverside if I remove client validation from it. But when I am implementing IClientValidatable on the attribute, it gives me an error:

"Validation type names in unobtrusive client validation rules must be unique."

Any help how can I solve it??


Solution

  • Finally here I found the answer my-self. Look at following article for solution http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx