views:

37

answers:

1

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

    <DisplayName("website")> _
    <StringLength(256, ErrorMessage:="Web Address cannot 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.

+1  A: 

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>.

Darin Dimitrov
Maybe it's just because I don't read C# all that well, but that sure looks complicated.
rockinthesixstring
That's the only way. Client validation works by inspecting the attributes you've used and generating the necessary javascript code. When you write a custom validation method there's no way for automatic javascript generation. What if in your validation method you used reflection or called an external web service to perform the validation. How do you expect the client validation to automagically works?
Darin Dimitrov
No I get that, I just "ASS-umed" that since the custom validator that I'm using is actually deriving from the base REGEX validator, that there would be some auto magic that would build it for me. There's no point in simplifying my Service Layer validation with a custom Regex validator if I still have to write the Javascript manually. I was just hoping that I could reuse the actual regex over and over for simpler implementation without copy/paste.
rockinthesixstring