Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetClientValidationRules is never called in MVC application

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.

like image 829
Kyro Avatar asked Nov 10 '22 06:11

Kyro


1 Answers

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.

like image 193
Sasha Avatar answered Nov 14 '22 21:11

Sasha