Reputation: 33
I am trying to do some validation checks on inputs, which I'm having some issues with. I need to be able to check that the url entered is valid, return it's boolean value. If true it allows it to be assigned as myURL, else it will give me the JOptionPane message and stop. These will be checked from fields of entered data. This is part of a larger project, so any and all input is welcomed and appreciated.
public String SetURL (String a) {
if (ValidateURL(a)) {
myURL = a;
}
else {
JOptionPane.showMessageDialog (null, "Sorry the URL: " + SetURL() + " is an invalid URL",
"Incorrect Information", JOptionPane.INFORMATION_MESSAGE);
}
}
public Boolean ValidateURL () {
//Some code here to check the validation and return a true of false
}
Upvotes: 0
Views: 624
Reputation: 688
You can to use regex and the Java Matcher class.
Here is a good regex: (http:(?![^"\s]*google)[^"\s]+)["\s]
and here is the documentation on Matcher.
Upvotes: 0
Reputation: 136
You need to create both a URL
object and a URLConnection
object. The following code will test both the format of the URL and whether a connection can be established:
try {
URL url = new URL("http://www.yoursite.com/");
URLConnection conn = url.openConnection();
conn.connect();
} catch (MalformedURLException e) {
// the URL is not in a valid form
} catch (IOException e) {
// the connection couldn't be established
}
in your case, the catch will give you the JOptionPane message and stop, and you can even tell the user if it is because it's malformed or unavailable
Upvotes: 3