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

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
}

Leave a Reply

Your email address will not be published. Required fields are marked *