HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Data validation for preventing blank entries

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
blankvalidationforpreventingdataentries

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: ");

Code Snippets

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;
}
String name = getNonBlankInput("Enter name: ");

Context

StackExchange Code Review Q#889, answer score: 5

Revisions (0)

No revisions yet.