Question

i want to check a list of textfield with a validation loop function

if anyone can explain me how to do this thks ;)

i do this :

 public void  validation()
    {
       List<String> list = new ArrayList<>();
       list.add("LastNameTextField");
       list.add("nameTextField");
       list.add("ageTextField"); 
       list.add("AdressTextField");        
       list.add("PhoneTextField1");        


       for(String check :list )
       {
          if(validator((check.toString()).toString()))
/*here i just want to get the field name and this value */
             JOptionPane.showMessageDialog(null, check+ " Empty value");
       }


    }

    public static boolean validator(String TextFieldTextToCheck)
    {
       if ((TextFieldTextToCheck== null) || (TextFieldTextToCheck.length() == 0)) {
            return true ;
        }
       else return false;
    }

i dont find the way to get the field value if anyone can help
thank you for your time

Was it helpful?

Solution

For the record, I don't have allot of Java experience. If I understand correctly, you are trying to validate the contents of several TextFields in a GUI. And the validation only makes certain that the textfield is empty. I would recommend that instead of using a collection of the textField names, you simply use a collection of references to the textfields you wish to validate.

So your ArrayList is populated with textfield references instead:

ArrayList<TextField> textFields = new ArrayList<TextField>();
textFields.add(textbox1);
textFields.add(textbox2);
textFields.add(textbox3);
textFields.add(textbox4);

You iterate through the ArrayList like before. I used a System.Out call for my own testing.:

for(TextField textField : textFields) {
    if(validateTextField(textField)) {
        //JOptionPane.showMessageDialog(null, textField.getText() + " Empty value");
        System.out.println(textField.getName() + " has an Empty value");
    }
}

The validate function now looks like this. I added a test for a NULL reference, but you could leave that out.:

public static boolean validateTextField(TextField textField) {
    if(textField == null) throw new NullPointerException("The validate function received a null textfield reference. Check your loop.");
    return textField.getText().length() == 0;
}

OTHER TIPS

Your if condition is incorrect.

    if(validator((check.toString()).toString()))

It should be corrected as:

   if(YourClass.validator(check))

Explanation:

  1. check is already String. There is not need to call toString() on it.

  2. validator method is a static method so call it in static way as YourClass.validator where YourClass is your class name.

  3. validator method return boolean and if expects boolean so no need to get a String again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top