Problem
I want to create a validation wherein blank entries will not be accepted. So if I call this code:
entry[i].setName(JOptionPane.showInputDialog("Enter Name: "));
if the entry is blank, it will not be accepted and an error will prompt:
it cannot accept blank entries. Of course it could easily remedied with this code:
String name = JOptionPane.showInputDialog("Enter Name: ");
while (name.equals("")){
JOptionPane.showMessageDialog(null, "Cannot accept blank entries!");
name = JOptionPane.showInputDialog("Enter Name: ");
}
but if I want to validate 100 fields that I don’t want to have a blank entry, then my code will be messy and long.
How could I do it better? I’ve read about using getters and setters or the try-catch methods to do the validation but I don’t know if this kind of validation is applicable. And I don’t know how I can do it. And if it is applicable, would I be violating the Model-View-Controller concept if I included a JOption
message dialog box on my getter and setter methods? What code does programmers usually use in doing blank entries validation?
Solution
Extract the input code into a method:
String getNonBlankInput(String prompt) {
String input = JOptionPane.showInputDialog(prompt);
while (input.equals("")) {
JOptionPane.showMessageDialog(null, "Cannot accept blank entries!");
input = JOptionPane.showInputDialog(prompt);
}
return input;
}
Usage:
String name = getNonBlankInput("Enter name: ");
You should really look at the java validation standard, specifically JSR303.
Hibernate Validator is the reference implementation, take a look at their documentation.
To provide a simple example
public class Foo {
@NotNull(message = "property bar must be provided")
@Pattern(regexp = "[a-z0-9]", message = "property bar must contain only letters and numbers")
private String bar;
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Foo foo = new Foo();
Set<ConstraintViolation<Foo>> constraintViolations = validator.validate(foo);
// now you have a Set of ConstraintViolations, if something is not working
Use the existing standards, no need to reinvent the wheel.
Please change the validating condition like this.
while ("".equals(input.trim())) {
JOptionPane.showMessageDialog(null, "Cannot accept blank entries!");
input = JOptionPane.showInputDialog(prompt);
}
This type of validation may also check only blanks as input & any other value also.
1. String name = JOptionPane.showInputDialog("Enter Name: "); contains spaces.
2. String name = JOptionPane.showInputDialog("Enter Name: "); contains null.