2

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Maybe it's just because I don't read C# all that well, but that sure looks complicated.
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?
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.
You don't have to write javascript if you are inheriting from RegExValidator. All you got to do is register the RegularExpressionAttributeAdapter as the adaptor for your new Validation attribute. See this: stackoverflow.com/questions/2383669/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.