I am trying to validate s String url in my java application using @Pattern annotation of the javax validation library.
@Pattern(message = "Must be a valid URL", regexp = "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\ ~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\ .~#?&//=]*)")
When i submit a url in the url in this format; https://www.test.com it is successful but url in this format https://api-apps.testapp.systems/test-service/v1/test, it fails the validation.
The issue is with the .com The same url with .systems fail but with .com passes.
How can i make my regular expression allow all kinds of urls .com, .edu or .systems regardless ??
CodePudding user response:
You can use the @URL Annotation or org.apache.commons.validator.UrlValidator to do that.
Example:
UrlValidator crunchifyURLValidator = new UrlValidator();
String url = "https://crunchify.com";
if (crunchifyURLValidator.isValid(url)) {
crunchifyLog("Hey. URL " url " is valid");
} else {
crunchifyLog("Hey. URL " url " is not valid");
}
CodePudding user response:
The issue was with the lenght of string permitted by the regexp for the TLD, which was {1,6}--
.[a-zA-Z0-9()]{1,6}\\b i expanded the range and it accommodated a longer TLD name.
