I use MaskFormatter with JFormattedTextField for two fields, in which I request phone numbers.
Photo:
Then, I have a button called "Calculate", where I have the following to validate that the fields are not empty:
if(validarCampos(txtNumeroDeOrigen, txtNumeroDeDestino, txtDuracion)) {
}
So, I have this function to do the validations:
public boolean validarCampos(JFormattedTextField txtNumeroDeOrigen, JFormattedTextField txtNumeroDeDestino, JTextField txtDuracion)
{
if(txtNumeroDeOrigen.getText().replaceAll("[()-_]", "").trim().length() == 0
&& txtNumeroDeDestino.getText().replaceAll("[()-_]", "").trim().length() == 0
&& txtDuracion.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "Debe agregar un numero de origen.\nDebe agregar un numero de destino.\nDebe agregar la duracion.");
return true;
}
else if(txtNumeroDeOrigen.getText().replaceAll("[()-_]", "").trim().length() == 0
&& txtNumeroDeDestino.getText().replaceAll("[()-_]", "").trim().length() == 0)
{
JOptionPane.showMessageDialog(null, "Debe agregar un numero de origen.\nDebe agregar un numero de destino.");
return true;
}
}
I have used the following to know if the JFormattedTextField field is empty:
.getText().replaceAll("[()-_]", "").trim().length() == 0
But for some reason it doesn't work for me, it keeps telling me that the fields are empty when in fact they already have numbers.
Photo of the present problem:
Isn't that the correct way to validate a MaskFormatter? Which?
One way would be , Replacing everything that is not a number using the method replaceAll(String regex, String replacement) and then accessing
Length
it and checking if it is 0The function to validate would be like this:
Stop in your
if
call to said method, and there launch the corresponding Message