Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Validation Problem

public void actionPerformed( ActionEvent event )
{
if ( event.getSource() == moneyIn ) // if Money In button is pressed
{
//read in From Date and To Date from user as a string

fromDate = JOptionPane.showInputDialog( "Enter From Date" );
do
{
JOptionPane.showMessageDialog(null, "From Date must be in the format dd/MM/yy", "Validation Error", JOptionPane.WARNING_MESSAGE);
fromDate = JOptionPane.showInputDialog( "Enter From Date" );
}
while (!fromDate.matches("^((0?[1-9])|(1\\d)|(2\\d)|(3[0-1]))\\/((0?[1-9])|(1[0-2]))\\/(\\d\\d)"));

toDate = JOptionPane.showInputDialog( "Enter To Date" );
do
{
JOptionPane.showMessageDialog(null, "From Date must be in the format dd/MM/yy", "Validation Error", JOptionPane.WARNING_MESSAGE);
toDate = JOptionPane.showInputDialog( "Enter To Date" );
}
while (!toDate.matches("^((0?[1-9])|(1\\d)|(2\\d)|(3[0-1]))\\/((0?[1-9])|(1[0-2]))\\/(\\d\\d)"));

// create JTextArea to display output
JTextArea outputTextArea = new JTextArea();

// set first line of text in outputTextArea
outputTextArea.setText( "From Date\t To Date\t Amount\n" );

// append one line of text to outputTextArea
outputTextArea.append( fromDate + "\t" + toDate + "\t" + amount + "\n" );

// display results
JOptionPane.showMessageDialog( null, outputTextArea,
"Money In", JOptionPane.INFORMATION_MESSAGE );
}

I am trying to get this bit of testing validation code working. The two do while statements are meant to check what the user inputs and if its wrong, show an error and ask them to re-enter it. The current method only works if the user enters it wrong the first time, but always brings up the error if its right the first time.

What can I do to overcome this problem?
[1944 byte] By [hshah] at [2007-11-11 8:00:49]
# 1 Re: Validation Problem
You should try to use a boolean helper for checking:

...
if ( event.getSource() == moneyIn ) // if Money In button is pressed
{
boolean isOK = false;
while (!isOK){
fromDate = JOptionPane.showInputDialog( "Enter From Date" );
if (fromDate.matches("^((0?[1-9])|(1\\d)|(2\\d)|(3[0-1]))\\/((0?[1-9])|(1[0-2]))\\/(\\d\\d)"))
isOK=true;
else JOptionPane.showMessageDialog(null, "From Date must be in the format dd/MM/yy", "Validation Error", JOptionPane.WARNING_MESSAGE);
} // end while
...

same for all other dialogs.
graviton at 2007-11-11 22:36:40 >