How to further validate a jTextBox in Java to allow dots and commas? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to further validate a jTextBox in Java to allow dots and commas? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I currently have this to allow numbers and to delete the numbers, i would like to add validation to allow “.” and “,” but i’m slightly unsure. I’ve tried this. Not sure what is exactly wrong, (very new sorry).

public void keyTyped(KeyEvent e) {
                // allows only numbers, back space, delete, and slash.
                char c = e.getKeyChar();
                if (((c < '0') || (c > '9') || (c == ',') ||(c == '.')) && (c != KeyEvent.VK_BACK_SPACE) && (c != KeyEvent.VK_DELETE)
                        && (c != KeyEvent.VK_SLASH)) {
                    e.consume(); // ignore event
                }
            }

Answer

Problem is that you use &&(and) operator, change all operators to ||(or)

EDIT
My bad didn’t read what you really want to do. This should work:

if ((c < '0') || (c > '9')) && (c != ',') && (c != '.') &&
(c != KeyEvent.VK_BACK_SPACE) && (c != KeyEvent.VK_DELETE) 
                        && (c != KeyEvent.VK_SLASH)) {
    e.consume(); // ignore event
}
We are here to answer your question about How to further validate a jTextBox in Java to allow dots and commas? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji