Search code examples
c#jqueryasp.net-mvcunobtrusive-validation

Jquery Validation Works with Default [Required] but not with custom class


Based on the following link: Multi Language - Data Annotations Make a series of classes to translate the texts of the Data Annotation. Everything works fine on the server side, but client side validation does not work.

If i use: [System.ComponentModel.DataAnnotations.Required] public string Name { get; set; }

Validation on the client side works correctly, but if I use:

[Infrastructure.Required]//My custom class public string Name { get; set; }

It works only on the server side.

This is the class that I am currently using:

namespace project.Infrastructure
{
public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string _displayName;
    public RequiredAttribute()
    {
        ErrorMessageResourceName = "Validation_Required";
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        _displayName = validationContext.DisplayName;
        return base.IsValid(value, validationContext);
    }
    public override string FormatErrorMessage(string name)
    {
        var msg = WebsiteTranslations.GetTranslationErrorMessage(Settings.LanguageId, "Required", WebsiteTranslations.GetTranslation(name, 1, Settings.LanguageId));
        return string.Format(msg, _displayName);
    }
    public System.Collections.IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
    {
        return new[] { new ModelClientValidationRequiredRule((ErrorMessage)) };
    }
  }
}

Solution

  • I get the answer from this post: validation-type-names-in-unobtrusive The GetClientValidationRules Method is like this:

        public IEnumerable GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
        {
            var clientValidationRule = new ModelClientValidationRule()
            {
                ErrorMessage = FormatErrorMessage(ErrorMessage),
                ValidationType = "required"
            };
            yield return new[] { clientValidationRule };
        }
    

    And in the Application_Start inside Global.asax:

          DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(RequiredAttributeAdapter));
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(StringLengthAttributeAdapter));