2

I've tried to extend the RequiredAttribute to make some localizations. I wrote this:

public class LocalizedRequiredAttribute : RequiredAttribute

{
    public LocalizedRequiredAttribute(string errorMessageResourceName)
    {
        this.ErrorMessageResourceName = string.IsNullOrEmpty(errorMessageResourceName) ? "Required_ValidationError" : errorMessageResourceName;
        ErrorMessageResourceType = typeof(bop.Core.Resources.Label);
    }
}

At the client side no validation message is rendered. What is wrong? Thanks for help. Luca

User907863
  • 407
  • 1
  • 6
  • 16

2 Answers2

4

In your followup comment, you specified that clientside validation wasn't working. It looks like you asked this same question here, but for the sake of StackOverflow, I will provide the answer.

The LocalizedRequiredAttribute class must also implement IClientValidatable to get clientside validation to work:

using System.Web.Mvc;
public class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable
{
    // your previous code

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            // format the error message to include the property's display name.
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),

            // uses the required validation type.
            ValidationType = "required"
        };
    }
}
scott.korin
  • 2,458
  • 2
  • 21
  • 34
1

Take a look at this and this posts by Darin Dimitrov.

Hope this helps.

Community
  • 1
  • 1
Gabe Thorns
  • 1,406
  • 15
  • 20
  • Hi Darin, thanks for links. I've tried your code: ` public class LocalizedRequiredAttribute : RequiredAttribute { public LocalizedRequiredAttribute(string resourceTag) { ErrorMessage = GetMessageFromResource(resourceTag); } private static String GetMessageFromResource(String resourceTag) { return ResourceManager.Current.GetResourceString(resourceTag); } } ` but I get an error in "ResourceManager.Current". – User907863 Oct 26 '11 at 14:47
  • I resolved in part. Now the LocalizedAttribute validates only server side, and not client side... but if I use the base Attribute work fine in my client. Any idea? Thanks. Luca – User907863 Oct 26 '11 at 16:23