1

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?

larry
  • 11
  • 1
  • 2
    Where is your client-side code? – Jeroen Heier Jan 11 '17 at 19:11
  • Do you have `jqueryval` on your view? – Hadee Jan 11 '17 at 19:46
  • Sounds like you're mistaken in how the client side validation happens. See http://stackoverflow.com/questions/4747184/perform-client-side-validation-for-custom-attribute – ChiralMichael Jan 11 '17 at 19:49
  • You need to include client side scripts to add methods to the `$.validator`. Recommend you read [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Jan 11 '17 at 20:07

0 Answers0