Halley's Blog

Data Validation in Java Swing

Posted in Java by Halley on April 8, 2009

Any Graphical User Interface application will interact with the user to gather the input. After the necessary information is gathered from the user, the application may store it in a database, perform manipulations on the entered data etc. But before we do something with the data, we need to check it for its correctness. For example, if we are accepting a date from a user, we may need to check whether if it falls within some specific range, if we are accepting an e-mail id, we must check it to verify if it is in the correct format. This process is known as data validation.

Data validation process in Swing can be done using a class called InputVerifier. The purpose of this class is to ensure that the text entered by the user is valid before allowing the user to navigate the user out of the textfield. To do this, we must create a subclass of InputVerifier and attatch an instance of their subclass to the JComponent whose text they want to validate

The InputVerifier class has a verify() method. Let me explain, steb by step what is going to happen.

  1. The user moves the cursor a field. Focus is shifted to it.
  2. The user enters some data and tries to shift focus out of the field.
  3. Before focus is shifted, the InputVerifier class’s verify() method is called.
  4. The verify() function will return either true or false depending on the status of validation.
  5. If the function returns true, the focus is shifted to a new component.
  6. And if it returns false, focus remains at the component.

Heard the proverb, “An apple a day keeps the doctor away!”? Well, I love apples. Especially the red jucy ones. And as a dedication to my love of apples, lets make a small textfield that accepts only the word apple and nothing else!

Here is the code to the AppleLover class..


class AppleVerifier extends InputVerifier
{
@Override
public boolean verify(JComponent input) {
//Get the text in the textfield
JTextField appleLover=(JTextField)input;
//check if the user has entered anything else
if(appleLover.getText().equalsIgnoreCase("apple"))
{
//good guys love apples.
//returns true to to ensure that focus is moved to where
//the user requires it
return true;
}
else
{
//fire a warning shot!!
//and return false to make sure focus is not moved out
JOptionPane.showMessageDialog(input, "Only apples please!!!",
"Oh no you wont!!", JOptionPane.ERROR_MESSAGE);
return false;
}
}
}

And now, all we have to do is attach the instance of the above class to our textfield! And now, only apples are allowed in our textfields. Other fruits now won’t stand a chance!

JTextField iLoveAppleField=new JTextField("");
iLoveAppleField.setInputVerifier(new AppleVerifier());

The process can be done in NetBeans or any other IDE. I will show how it can be done in NetBeans.

Add the AppleVerifier class file to the package in which the GUI belongs. Now right click on the JTextField which you want to validate.

blog1

And then, add the instance of the appropriate InputVerifier class by selecting Custom Code option.
blog2
Data validation is a tricky business, and to aid users in the process, Java now supports Regular Expressions. For eg, if you want to validate a field accepting e-mail ids, you can use the following code to check the validity of the data.
re="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)";
if(badEmail.getText().matches(re)){
     }
If you want to validate a date in the format DD-MM-YYYY
re="(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d";
if(evilDate.getText().matches(re))
And now, to validate in the format, MM-DD-YYYY
re="(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d"
if(evilDate.getText().matches(re))
And to find more about regular expressions, www.regular-expressions.info.
And you can download a sample code which demonstrates the above discussed features here.
You need NetBeans 6.5 to view and edit the code.
Well, that’s it for now!! Have a hot coffee and start coding!!
Advertisements