I'm writing a URL validator. Firstly, it checks for special characters in the input. Secondly, it adds 'http://' and checks for validity.
/* Returns true if url is valid */
private static boolean isValidURL(String url) {
boolean containsSpecialCharacters = specialCharactersExists(url);
if ( !containsSpecialCharacters ) {
/* Try creating a valid URL */
try {
new URL(String.format("%s%s", "http://", url)).toURI();
return true;
} catch (Exception e) {
/* Not a valid URL */
}
}
return false;
}
/* Returns true if url contains special characters */
private static boolean specialCharactersExists(String input) {
Pattern regex = Pattern.compile("[^A-Za-z0-9.-]");
Matcher matcher = regex.matcher(input);
return matcher.find();
}
This serves my purpose. I'm seeking advice on how to improve the code (especially the Regex part)