How to validate website URL field of an JPA entity?
Asked Answered
G

2

5

I have a JPA entity representing a company. It has a field representing the company's website URL. I need to validate that the URL is a valid website URL prior to persisting. I suppose only URLs starting with http or https would be valid website URLs. How can I enforce this? I'm using the latest. version of Hibernate as my JPA provider.

Gaiseric answered 30/8, 2017 at 21:23 Comment(2)
For better illustration: JPA annotation are on data (model). Live effects of validation should be seen on GUI layer. Something must connect both. The best is use complete framework (web framework for web app), not 'manual' code,Trimorphism
JPA is NOTHING to do with Bean Validation. That is the Bean Validation APIIndevout
T
11

@dimitrisli suggests you a correct solution. You should use @URL constraint. If you want to allow a specific protocol - there's a protocol attribute for this constraint:

@URL(protocol = "http")
private String companyUrl;

In addition there's also a regexp attribute which you can use to make your urls to match any pattern you'd like.

    @URL(regexp = "^(http|ftp).*")
    private String companyUrl;

You can check for more details in the doc (look for URL in the linked section).

Also if you'd like to use the URL instead of String, you can write your own validator implementation for URL class and URL constraint, but note if you'd try to create an invalid URL it will fail during creation process and not when validated. So writing a validator for URL might make sense only if you'd like to check the protocol and things like that.

To write your own validator you would need to implement

public class URLValidator implements ConstraintValidator<org.hibernate.validator.constraints.URL, URL> {
...
}

for more details check out this blog post.

Thesda answered 31/8, 2017 at 7:36 Comment(3)
The regexp doesn't work for me. If I validate google.com against the URL validator with the regexp = "^(http|https)" , it fails validation.Gaiseric
Right... It's because it's trying to match that expression to a String value and in your case of google - it doesn't start with protocols. .. But is it a valid URL though ? (I mean if it's without a protocol)Thesda
I figured it out. It's because the regexp is matching the whole string not just the occurrence of the sibstring. I needed to add .* such that the regexp = "^(http|https).*"Gaiseric
P
0

Take a look at the @URL annotation of Hibernate Validator.

Polytrophic answered 30/8, 2017 at 21:39 Comment(1)
Thanks. That means I would need to represent the website URL field as a 'String' instead of a 'java.net.URL'. I suppose that is OK. But how do I specify multiple protocols such as 'http' and 'https'. The '@URL' 'protocol' attribute only takes a single 'String'. Don't think I should allow protocols such as 'file', 'ftp', etc.Gaiseric

© 2022 - 2024 — McMap. All rights reserved.