Satish Sharma
Satish Sharma

Reputation: 3294

URL validation Without protocol

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

Answers (3)

Isabella
Isabella

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

Santosh
Santosh

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

  1. Create a custom URL validator (either by extending URLValidator or use composition).
  2. Inside its validate method, check if the URL has protocol string in the beginning or not. If its not present add it and invoke the URLValidator to actually validate the URL.

Upvotes: 0

TheHe
TheHe

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

Related Questions