Is it possible to implement client-site validation for custom ValidationAttribute, which is used in Class scope? For example my MaxLengthGlobal, which should assure global max limit for all input fields.
[AttributeUsage(AttributeTargets.Class)]
public class MaxLengthGlobalAttribute : ValidationAttribute, IClientValidatable
{
public int MaximumLength
{
get;
private set;
}
public MaxLengthGlobalAttribute(int maximumLength)
{
this.MaximumLength = maximumLength;
}
public override bool IsValid(object value)
{
var properties = TypeDescriptor.GetProperties(value);
foreach (PropertyDescriptor property in properties)
{
var stringValue = property.GetValue(value) as string;
if (stringValue != null && (stringValue.Length > this.MaximumLength))
{
return false;
}
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = this.FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "maxlengthglobal",
};
rule.ValidationParameters.Add("maxlength", this.MaximumLength);
yield return rule;
}
}
Thank you.
Nope, it's not possible. Sorry.