Search code examples
c#asp.net-mvc-2asp.net-mvc-2-validation

Client Side Validation Not working for custom Attribute


Hi I have a custom Attribute

 public class NameAttribute : RegularExpressionAttribute
 {
     public NameAttribute() : base("abc*") { }
 }

This works on the serverside but not in the client side but this

[RegularExpressionAttribute("abc*",ErrorMessage="asdasd")]
public String LastName { get; set; }

works on both. I read this but it does'nt help.

I would really appreciate your assistance.

Thank you


Solution

  • You might need to register a DataAnnotationsModelValidatorProvider associated to this custom attribute in Application_Start:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    
        DataAnnotationsModelValidatorProvider.RegisterAdapter(
            typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)
        );
    }
    

    You might also checkout the following blog post.

    And here's the full example I used to test this.

    Model:

    public class NameAttribute : RegularExpressionAttribute
    {
        public NameAttribute() : base("abc*") { }
    }
    
    public class MyViewModel
    {
        [Name(ErrorMessage = "asdasd")]
        public string LastName { get; set; }
    }
    

    Controller:

    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            if (!ModelState.IsValid)
            {
    
            }
            return View(model);
        }
    }
    

    View:

    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcValidation.js") %>"></script>
    
    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm()) { %>
        <%= Html.LabelFor(x => x.LastName) %>
        <%= Html.EditorFor(x => x.LastName) %>
        <%= Html.ValidationMessageFor(x => x.LastName) %>
        <input type="submit" value="OK" />
    <% } %>
    

    Plus the Application_Start registration I showed earlier.