How to validate if a text field is numeric in Java?

3

How to validate if a text field is numeric in Java? I have validations for textfields that receive Strings, and it warns me when it's empty.

boolean Valida(){
    if(txtRFC.getText().equals("")){
        javax.swing.JOptionPane.showMessageDialog(this, "Llene todos los campos");
        return true;
    } 
        return false;
}//Validaciones

How do I do it this way, but limiting the field to Integers?

    
asked by skywalker14117 06.06.2018 в 22:46
source

2 answers

2

To validate if it has no value you can use the .isEmpty ()

if(txtRFC.getText().isEmpty()){
...
..
  

.isEmpty () Returns true if and only if length () is 0.

You can also combine the .trim() method to eliminate possible blank spaces.

if(txtRFC.getText().trim().isEmpty()){
...
..
  

How do I do it this way, but by the time the textfield has to   receive Integers?

Now to validate if the value is numeric, you can create a method to verify if the value you enter is numeric.

public static boolean esNumerico(String valor){     
    try{
        if(valor!= null){
            Integer.parseInt(valor);
        }
    }catch(NumberFormatException nfe){
         return false; 
    }
    return false;
}

You can use it in this way (with .trim() to avoid blank spaces).

if(!esNumerico(txtRFC.getText().trim()){
   //Valor no es numérico.
}else{
  //Valor ES numérico.
}
    
answered by 06.06.2018 в 23:21
0

To validate if a field is numeric you can try to convert the value to int with parseInt and return true or false depending on the result. This method would also give error in case of leaving the textField empty, although it would be more correct to verify empty fields with isEmpty() .

public boolean checkInteger() {
 try { 
    Integer.parseInt(txtRFC.getText()); 
 } catch(NumberFormatException e) { 
    return false; 
 }
 return true;
}
    
answered by 06.06.2018 в 23:19