开发者

ASP.NET MVC How to get Custom Validators to work with Client Side Validation

开发者 https://www.devze.com 2023-01-05 04:11 出处:网络
The following validation works fine on both client side and server side <DisplayName(\"website\")> _

The following validation works fine on both client side and server side

    <DisplayName("website")> _
    <StringLength(256, ErrorMessage:="Web Address ca开发者_运维百科nnot exceed 256 characters.")> _
    <RegularExpression("^http(s?)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$", ErrorMessage:="Not a valid website address")> _
    Public Property WebSite As String

However this validation only works on the Server side

    <DisplayName("website")> _
    <StringLength(256, ErrorMessage:="Web Address cannot exceed 256 characters.")> _
    <Website(ErrorMessage:="Not a valid website address")> _
    Public Property WebSite As String

Where my custom WebsiteAttribute looks like this

Public Class WebsiteAttribute : Inherits RegularExpressionAttribute
    Public Sub New()
        MyBase.new("^http(s?)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$")
    End Sub
End Class

I'm obviously missing something very simple.

Thanks in advance.


Take a look at this blog post from Phil Haack which demonstrates how to setup client validation for custom attributes. Basically you will need to write and register a custom DataAnnotationsModelValidator<T>.

0

精彩评论

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