繁体   English   中英

客户端验证不适用于自定义属性

[英]Client Side Validation Not working for custom Attribute

嗨,我有一个自定义属性

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

这适用于服务器端,但不适用于客户端,但这样

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

适用于两者。 我看了这个,但它没有帮助。

我非常感谢你的帮助。

谢谢

您可能需要在Application_Start注册与此自定义属性关联的DataAnnotationsModelValidatorProvider

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter)
    );
}

您还可以查看以下博客文章

这是我用来测试这个的完整例子。

模型:

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

public class MyViewModel
{
    [Name(ErrorMessage = "asdasd")]
    public string LastName { get; set; }
}

控制器:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {

        }
        return View(model);
    }
}

视图:

<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" />
<% } %>

加上我之前展示的Application_Start注册。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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