1

If I annotate field with @URL:

@URL
private String myUrl;

and try to set value to it without schema (google.com instead http://google.com)

then it will throw ConstraintViolationException.

How I can let to accept URLs without schema?

2 Answers 2

4

As part of the validation routine in UrlValidator a java.net.URL object with the given value is instantiated. Its constructor doesn't except URLs without protocols, thus the constraint is considered invalid. If you want to accept URLs without protocols, you could either use a regular expression via @Pattern or create a custom validator for the @Url constraint providing the logic you need.

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

Comments

2

As far as I remember you can use that annotation on getter - inside that method you can specify that schema should be added if it's not present already. You can even go as far as creating virtual property getter:

String getMyUrl() {
    return myUrl;
}

@URL
String getMyUrlWithSchema() {
    return (myUrl != null &&
               !myUrl.startsWith("http://") &&
               !myUrl.startsWith("https://")) ?
           "http://" + myUrl :
           myUrl;   
}

Alternatively you can write your own validator.

Comments

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.