Client side validation doesn't work when inheriting from RequiredAttribute in ASP.NET MVC 3?

I created a legacy attribute similar to this in ASP.NET MVC3:

public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
    public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
    {
        this.ErrorMessageResourceName = errorResourceName;
        this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
    }
}

And use it as follows:

[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }

This did not work, and MVC ignored it. Then I create a simpler class that is just inherited from RequiredAttribute as follows:

public class MyRequiredAttribute : RequiredAttribute
{
}

I use it as I said. But that did not work.

Although all of these methods work fine with DisplayNameAtrribute.

What is the problem?

+5
source share
2 answers

You can fix this by adding the following code to Global.asax: (found the answer here )

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredLocalizableAttribute), typeof(RequiredAttributeAdapter));

, marcind, , ModelClientValidationRequiredRule . , :

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string msg = FormatErrorMessage(metadata.GetDisplayName());
        yield return new ModelClientValidationRequiredRule(msg);
    }
+3

, . , MVC .

, IClientValidatable:

public class MyRequiredAttribute : IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
         yield return new ModelClientValidationRequiredRule();
    }
}
+3

All Articles