Results 1 to 17 of 17
  1. #1
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default Validate url in a JTextField

    Hi,
    I have to write a function that will check whether a string inserted into a JTextField is a valid url address - I don't need to check whether it really exist, I just need to make sure that it has a form of a valid website address.

    I know how to verify if there are only digits or letters or whether the user has inserted a date in a requiered format into a JTextField, but I can't find a solution to this problem.

    I would be grateful if anyone could help.

  2. #2
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    305
    Rep Power
    6

    Default

    This sounds like a problem that can be solved with Regular Expressions.
    Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)

  3. #3
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    If you look at the URL class API, you will notice the public URL(String spec) constructor throws a MalformedURLException. So, get the String from the JTextField, try to construct an URL instance, and return false if the exception is caught.
    To StormyWaters: your aproach is probably the point of this assignment, and learning regex is a very valuable skill for any programmer.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  4. #4
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Thanks for your replies. I have used the suggestion written by m00nchile and finally everything works fine. At first look those regular expressions didn't look easy but I will try to learn and use them as well.
    Once again thanks a lot for your help!

  5. #5
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Ok, so I have my JTextField and my method that will check whether the inserted string is in url format. Now I would like to verify the user's input when the JTextField loses focus.

    I have written a method "public void focusLost(FocusEvent e)" , I have registered the JTextField to this method and I have checked that this text field knows when it loses its focus but I don't know how to call my veryfiyng method on this text field - the focus is passed to the next text field and no verification takes place.

    Can anyone help?

  6. #6
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by knickerbocker View Post
    Can anyone help?
    Perhaps we need to see code.

  7. #7
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Here are the relevant parts of code:

    public class Validation {
    .
    .
    .
    public static boolean isUrl(String text){
    try{
    URL url = new URL(text);
    url.getPath();
    }
    catch (MalformedURLException e) {
    JOptionPane.showMessageDialog(null, "Invalid url", "Error",JOptionPane.ERROR_MESSAGE);
    return false;
    }
    return true;

    }

    public class MyFocusListener extends FocusAdapter {
    .
    .
    .
    public void focusLost(FocusEvent e) {
    JTextField field = (JTextField)e.getSource();
    }


    public class MyClass extends JFrame {
    .
    .
    .
    private JTextField field_Url = new JTextField();
    .
    .
    .
    field_Url.addFocusListener(MyFocusListener);
    .
    .
    .
    public void validateUrl(){
    //here I would like to verify the correctness of the user's input when the field_Email loses its focus
    }
    Last edited by knickerbocker; 05-29-2010 at 08:32 PM. Reason: correction

  8. #8
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    You'd be better off posting a small compilable program that demonstrates your problem (and please use code tags). I can't make much out of your little snippet above, maybe someone else can.

  9. #9
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by curmudgeon View Post
    You'd be better off posting a small compilable program that demonstrates your problem (and please use code tags). I can't make much out of your little snippet above, maybe someone else can.
    Thank you for your answer and suggestion to post the program. The code below will compile and the program will run:

    1.
    package mypackage;
    import java.awt.Container;
    import java.awt.FlowLayout;

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;



    public class MyClass extends JFrame {

    private static final long serialVersionUID = 1L;
    JTextField field_Url, field_Email;
    Container con;
    static String text = new String();

    public MyClass() {
    con = getContentPane();
    setBounds(0, 0, 400, 100);
    field_Url = new JTextField(30);
    field_Email = new JTextField(30);
    setLayout(new FlowLayout());
    con.add(new JLabel("Url:"));
    con.add(field_Url);
    con.add(new JLabel("Email:"));
    con.add(field_Email);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    MyFocusListener myFocusListener = new MyFocusListener();
    show();

    field_Url.addFocusListener(myFocusListener);
    field_Email.addFocusListener(myFocusListener);

    }

    public void validateUrl(){
    //here I would like to verify the correctness of the user's input when the field_Url loses its focus
    }

    public static void main(String[] args){
    new MyClass();
    }
    }


    2.
    package mypackage;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import javax.swing.JTextField;

    public class MyFocusListener extends FocusAdapter {

    public void focusGained(FocusEvent e) {
    JTextField field = (JTextField)e.getSource();
    //field.setText("got focus");
    }

    public void focusLost(FocusEvent e) {
    JTextField field = (JTextField)e.getSource();
    //field.setText("focus lost");

    }
    }

    3.
    package mypackage;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JOptionPane;


    public class Validation {

    public boolean url;

    public Validation(){
    String text = new String();
    this.url = isUrl(text);
    }

    public static boolean isUrl(String text){
    try{
    URL url = new URL(text);
    url.getPath();
    }
    catch (MalformedURLException e) {
    JOptionPane.showMessageDialog(null, "Invalid url", "Error",JOptionPane.ERROR_MESSAGE);
    return false;
    }
    return true;
    }
    }

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    With all your classes being external, you need to pass the address of a validation object to your focus listener. This could be done in the constructor. Then the focusGained/lost methods can call methods in the validation object.
    You might also look at Document listeners. There was a very recent post about how to use them. Try Searching this forum for the code.

  11. #11
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    I've not used this before, but what about using an InputVerifier:

    Java Code:
      public MyClass() {
        con = getContentPane();
        // .... etc...
    
        // **** don't need these ****
        //field_Url.addFocusListener(myFocusListener);
        //field_Email.addFocusListener(myFocusListener);
        
        field_Url.setInputVerifier(new MyInputVerifier(field_Url));
    
      }

    and:
    Java Code:
    class MyInputVerifier extends InputVerifier {
      private JTextField field;
    
      public MyInputVerifier(JTextField field) {
        this.field = field;
      }
    
      public boolean verify(JComponent arg0) {
        return Validation.isUrl(field.getText());
      }
      
    }

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    OP: When posting code, please use code tags so that your code retains its formatting and is easy to read. For instance, which is easier to read, the code in your post or that in curmudgeon's post? To do this, simply add the tag

    [code]

    above your block of code, and the tag:

    [/code]

    below the block.

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    I've never used it. Put it in your code and see what happens.

    Whoops, this was to another poster and not the OP.
    Last edited by Norm; 05-30-2010 at 03:07 PM. Reason: Missed who posted msg

  14. #14
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Actually, it can be simplified even more (sorry, I'm a newbie with regards to using this) as it doesn't need the constructor parameter since the verify method already gets a reference to the JTextField invoking it, and might as well simply use an anonymous inner class. Simplified code:

    Java Code:
        //field_Url.setInputVerifier(new MyInputVerifier(field_Url));
        field_Url.setInputVerifier(new InputVerifier() {
          @Override
          public boolean verify(JComponent arg0) {
            return Validation.isUrl(field_Url.getText());
          }
        });

    OK, I've got to stop doing this...
    Last edited by curmudgeon; 05-29-2010 at 11:12 PM.

  15. #15
    knickerbocker is offline Member
    Join Date
    May 2010
    Posts
    6
    Rep Power
    0

    Default

    Thank you for all your answers. I can validate the fields using focus listener now. The funny thing is the error message appears more than once if wrong url has been inserted and the field loses focus. But I will figure it out somehow.

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    Add a println() to both focusGained and focusLost() methods to show when they are called. That might show why two messsages.

Similar Threads

  1. unable to validate
    By sanser in forum Java Servlet
    Replies: 4
    Last Post: 10-28-2009, 09:41 AM
  2. validate between int and double
    By heartysnowy in forum New To Java
    Replies: 4
    Last Post: 10-05-2009, 07:15 PM
  3. Replies: 1
    Last Post: 01-30-2009, 06:44 PM
  4. How to validate date using SampleDateFormat
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 09:31 PM
  5. validate hex character
    By paul in forum New To Java
    Replies: 1
    Last Post: 07-25-2007, 09:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •