开发者

Client Side Validation Not working for custom Attribute

开发者 https://www.devze.com 2023-02-25 19:53 出处:网络
Hi I have a custom Attribute public class NameAttribute : RegularExpressionAttribute { public NameAttribute() : base(\"abc*\") { }

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开发者_如何学Python; }

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消