1

I'm attempting to create my own model validation attributes for an ASP.NET MVC project. I've followed the advice from this question but cannot see how to get @Html.EditorFor() to recognise my custom attributes. Do I need to register my custom attribute classes in the web.config somewhere? A comment on this this answer seems to be asking the same thing.

FYI the reason I'm creating my own attributes is because I want to retrieve the field display names and validation messages from Sitecore and don't really want to go down the route of creating a class with a ton of static methods to represent each text property, which is what I'd have to do if I were to use

public class MyModel
{
    [DisplayName("Some Property")]
    [Required(ErrorMessageResourceName="SomeProperty_Required", ErrorMessageResourceType=typeof(MyResourceClass))]
    public string SomeProperty{ get; set; }
}

public class MyResourceClass
{
    public static string SomeProperty_Required
    {
        get { // extract field from sitecore item  }
    }

    //for each new field validator, I would need to add an additional 
    //property to retrieve the corresponding validation message
}
Community
  • 1
  • 1
Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120

1 Answers1

1

This question has been answered here:

How to create custom validation attribute for MVC

In order to get your custom validator attribute to work, you need to register it. This can be done in Global.asax with the following code:

public void Application_Start()
{
    System.Web.Mvc.DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof (MyNamespace.RequiredAttribute),
        typeof (System.Web.Mvc.RequiredAttributeAdapter));
}

(If you're using WebActivator you can put the above code into a startup class in your App_Start folder.)

My custom attribute class looks like this:

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    private string _propertyName;

    public RequiredAttribute([CallerMemberName] string propertyName = null)
    {
        _propertyName = propertyName;
    }

    public string PropertyName
    {
        get { return _propertyName; }
    }

    private string GetErrorMessage()
    {
        // Get appropriate error message from Sitecore here.
        // This could be of the form "Please specify the {0} field" 
        // where '{0}' gets replaced with the display name for the model field.
    }

    public override string FormatErrorMessage(string name)
    {
        //note that the display name for the field is passed to the 'name' argument
        return string.Format(GetErrorMessage(), name);
    }
}
Community
  • 1
  • 1
Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120