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.
I found this answer while looking for a solution to the same problem, and came up with a workaround.
Instead of 1 ValidationAttribute, have 2:
1.) A ServerValidationAttribute will be on the class, and will not implement IClientValidatable.
2.) A ClientValidationAttribute will be on the field / property, and will implement IClientValidatable, but the IsValid override always returns true.
When executed on the client, the server attribute is ignored, and vice versa.
If you need to have a validation attribute on the class, chances are the validation happens against multiple fields. I dropped in some boilerplate code for passing additional parameters to the client validation method, but it's not working as I expected. In my actual code I have commented out the viewContext and dependentProperty1 vars, and just passed a "DependentProperty1" string to the second argument of the rule.ValidationParameters.Add method. For some reason, I'm getting an incorrect HtmlFieldPrefix. If anyone can help with this please comment...
Anyway, you end up with a viewmodel like this:
A client script like this:
And a view like this:
Then if you have client validation disabled, the
@Html.ValidationMessageFor(m => m)
is displayed instead of the one for the property.