0

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 

}

1
  • You first have to decide/define what it means for a URL to be "valid" Commented Mar 28, 2012 at 14:34

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the amazing response time. would replacing yoursite with my input work? If this formats, like follows? try { URL url = new URL(a); 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 }
I get an error stating that it cannot find the Symbol URL.I tried a similar solution earlier and I got an error also.
are you using eclipse ?, you should check if you imported the right packages : import java.net.URL; import java.net.URLConnection;
I'm using DR Java, and I certainly did not add the packages! So that would be why. Not sure why it occurred to me to get the packages for the IO and Malformed but not that... Compiles fine now. Tried in a seperate file and works a treat! Thank you for this help!
0

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.

1 Comment

Thank you for the response, I used the above method however.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.