How to Create a Validation Class in Java - dummies

How to Create a Validation Class in Java

By Doug Lowe

If you’re feeling really ambitious, you can create a separate class to hold methods that do data validation in Java. It’s a good idea to make the methods static so you don’t have to create an instance of the validation class to use its methods.

Also, to avoid parsing the data twice, write the validation methods so that they return two values: a boolean that indicates whether the data can be parsed and a primitive that provides the parsed value.

A method can return only one value, of course. The only way to coax a method to return two values is to return an object that contains both of the values, and to do that, you have to create a class that defines the object. Here’s an example of a class you could use as the return value of a method that validates integers:

public class IntValidationResult
{
 public boolean isValid;
 public int value;
}

And here’s a class that provides a static method named isInt that validates integer data and returns an IntValidationResult object:

public class Validation
{
 public static IntValidationResult isInt(
  JTextField f, String msg)
 {
  IntValidationResult result =
   new IntValidationResult();
  try
  {
   result.value =
    Integer.parseInt(f.getText());
   result.isValid = true;
   return result;
  }
  catch (NumberFormatException e)
  {
   JOptionPane.showMessageDialog(f,
    "Entry Error", msg,
    JOptionPane.ERROR_MESSAGE);
   f.requestFocus();
   result.isValid = false;
   result.value = 0;
   return result;
  }
 }
}

Here’s a method that uses the isInt method of this class to validate the textCount field:

public void buttonOKClick()
{
 IntValidationResult ir;
 ir = Validation.isInt(textCount,
  "You must enter an integer.");
 if (ir.isValid)
 {
  JOptionPane.showMessageDialog(Number2.this,
   "You entered " + ir.value,
   "Your Number",
   JOptionPane.INFORMATION_MESSAGE);
 }
 textCount.requestFocus();
}