简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM