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.
@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.
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 Take a look at the @URL annotation of Hibernate Validator.
© 2022 - 2024 — McMap. All rights reserved.