I would like to know if anyone could help me on validating form fields in java desktop. When should I perform the validations, at the field's focusLost or keyPressed, or another more appropriate way.
For example:
I have a field of type JFormatTextField
with the mask of ## / ## / #### (date), being the field that is mandatory, I want to exit the window, then I click the exit button, it validates the field anyway, because the validation is in the focus, another question and this validation being in the keyPress, if I do not press enter and leave the field it will not validate, what is the correct logic for this type of validation
private void txtDataCotFocusLost(java.awt.event.FocusEvent evt) {
if (txtDataCot.getText().equals(" / / ")) {
//Limpa o lixo no campo
txtDataCot.setValue(null);
//Mensagem de validação
MensagemPersJOptionPane.msgAttention(rootPane, "<html>Conflitos encontrados, Verifique:<br><br>‣ Informe a data do orçamento!</html>", MensagemPersJOptionPane.getMsgTitleValidacao());
txtDataCot.requestFocus();
}
}
InputVerifiers:
InputVerifier verifierQuant = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
final JTextComponent source = (JTextComponent) input;
String text = source.getText();
double number = Double.parseDouble(text.replace(".", "").replace(",", "."));
if (number == 0 && !sair.equals("Sair")) {
MensagemPersJOptionPane.msgAttention(rootPane, "<html>Conflito(s) encontrado(s), verifique! <br><br>‣ Não foi informada uma quantidade </html>",
MensagemPersJOptionPane.getMsgTitleValidacao());
return false;
} else {
return true;
}
}
};
InputVerifier verifierProduct = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
final JTextComponent source = (JTextComponent) input;
String text = source.getText();
if (text.length() == 0 && !sair.equals("Sair")) {
MensagemPersJOptionPane.msgAttention(rootPane, "<html>Conflito(s) encontrado(s), verifique! <br><br> ‣ O produto não foi informado</html>",
MensagemPersJOptionPane.getMsgTitleValidacao());
return false;
} else {
return true;
}
}
};
InputVerifier verifier = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
final JTextComponent source = (JTextComponent) input;
String text = source.getText();
if ((text.equals(" / / "))) {
MensagemPersJOptionPane.msgAttention(rootPane,
"<html>Conflitos encontrados, Verifique:<br><br>‣ Informe a data do orçamento!</html>",
MensagemPersJOptionPane.getMsgTitleValidacao());
return false;
} else {
return true;
}
}
};
Dropped in the constructor
txtQuant.setInputVerifier(verifierQuant);
txtProduto.setInputVerifier(verifierProduct);
txtDataCot.setInputVerifier(verifier);
Action for the exit button
private void ActionSair() {
this.dispose();
}