Reputation: 3294
I Have used URLValidator class in java to validate URL . But I Want that if user won't give any protocol in URL then also the validation should be returned as valid.
Explaned Correctly: If this is supplied in URL "http://www.google.com" then also it should be a valid URL and if "www.google.com" is supplied then also the validation should returned as valid URL.
I have tried a lot .Please Help me in this. Thanks In Advance.
Upvotes: 4
Views: 6287
Reputation: 21
The best thing to do would be to prepend http (because that is the default protocol for urls) if there is no protocol and then validate the url.
Upvotes: 1
Reputation: 17923
You requirement is very specific and cannot be generalized. The URLValidator
you are using validates correctly. The presence of a protocol string (like http://) is basic requirement for a URL to be valid. For your needs, you can do following
URLValidator
or use composition). URLValidator
to actually validate the URL.Upvotes: 0
Reputation: 2972
check if that works for you:
boolean foundMatch = false;
try {
Pattern regex = Pattern.compile("\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.matches();
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
Upvotes: 5