5

I have a custom ValidationAttribute that implements IClientValidatable. But the GetClientValidationRules is never called to actually output the validation rules to the client side.

There is nothing special about the attribute but for some reason it is never called. I've tried registering an adapter in Application_Start() but that also doesnt work.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class CustomAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return true;
    }
    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string errorMessage = FormatErrorMessage(metadata.GetDisplayName());

        yield return new ModelClientValidationRule { ErrorMessage = errorMessage, ValidationType = "custom" };
    }

    #endregion
}

public class CustomAdapter : DataAnnotationsModelValidator<CustomAttribute>
{
    public CustomAdapter(ModelMetadata metadata, ControllerContext context, CustomAttribute attribute)
        : base(metadata, context, attribute)
    {
    }
    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return this.Attribute.GetClientValidationRules(this.Metadata, this.ControllerContext);
    }
}

In Application_Start() I have:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomAttribute), typeof(CustomAdapter));

When I put a breakpoint inside GetClientValidationRules it is never hit.

Kyro
  • 748
  • 1
  • 12
  • 28
  • Do you use unobtrusive validation? If yes, have you turned it on in web.config? Have you applied this attribute to model's property? Do you render property with this attribute using standard mvc Html helpers like Html.TextBoxFor? – Lanorkin Jul 06 '14 at 07:53

1 Answers1

1

In order GetClientValidationRules() method to get called you must enable client-side validation support. It can be done in the following ways:

In the web.config (for all pages of application):

<appSettings>
    <add key="ClientValidationEnabled" value="true" />

Or on particular view only:

either

@{ Html.EnableClientValidation(); }

or

@(ViewContext.ClientValidationEnabled = true)

Please note it must go before

@using (Html.BeginForm())

statement.

If you are using jquery unobtrusive validation (which seems to be a standard currently), you'll also need to enable it:

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

in web.config or

@Html.EnableUnobtrusiveJavaScript()

for particular views.

Sasha
  • 8,537
  • 4
  • 49
  • 76