How to validate an empty textField that can accepts only integers?

13,048

Solution 1

Typically, when you are validating user input in Java, you will want to check for both null and empty string values. To check String objects for equality, you must use the .equals() method (not the == operator). Thus, a check for an empty String value might look something like this:

if ( val == null || val.trim().equals( "" ) )
{
    // handle empty String case
}
else
{
    // handle non-empty String case
}

Hope this helps

Solution 2

if(textField_1.getText().isEmpty()){
    JOptionPane.showMessageDialog(null, "enter text in textfield");  
}  
Share:
13,048
Anuradha
Author by

Anuradha

Working as Assistant Software Engineer

Updated on November 21, 2022

Comments

  • Anuradha
    Anuradha over 1 year

    I wrote like this; but it fails to integer only textfields

    if(textField_1.getText().length()==0)  
    
    JOptionPane.showMessageDialog(null, "enter text in textfield");  
    

    Please help...

  • Radu Murzea
    Radu Murzea about 12 years
    indeed, if you check Strings for equality, the equals method is the way to go. But the length method is very ok to check if a String is empty. Also, the getText method does not return null Strings.
  • harry
    harry about 12 years
    @user1213523 i am glad that i could help, you can accept my answer by clicking on right sign just below the vote mark.
  • Muneeb Mirza
    Muneeb Mirza about 10 years
    I think u had no need to add description of urself. Thanks for an easy solution though. :)