I'm trying to do a custom ValidationAttribute in ASP.NET MVC 5 with client side validation but I can't understand what is wrong: the validation works fine, but only server side. I wrote the custom attribute:
public class UserStringLengthAttribute : ValidationAttribute {
private int _lenght1;
private int _lenght2;
public UserStringLengthAttribute(int lenght2, int lenght1)
{
_lenght2 = lenght2;
_lenght1 = lenght1;
}
public override bool IsValid(object value) {
var typedvalue = (string)value;
if (typedvalue.Length != _lenght1 || typedvalue.Length != _lenght2)
{
ErrorMessage = string.Format("The length must be {0} or {1}", _lenght1, _lenght2);
return false;
}
return true;
} }
and the adapter:
public class UserStringLengthAttributeAdapter : DataAnnotationsModelValidator<UserStringLengthAttribute> {
public UserStringLengthAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
UserStringLengthAttribute attribute) :
base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
ModelClientValidationRule rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
ValidationType = "custom"
};
return new ModelClientValidationRule[] { rule };
} }
I registered it in the Global.asax.cs:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(UserStringLengthAttribute),
typeof(UserStringLengthAttributeAdapter));
and I used it in the metadata:
[Required]
[UserStringLength(11, 16)]
[Display(Name = "VAT or tax code")]
public string CodVat;
but the validation works only in server side and not in client side....any suggestion?