Link to home
Start Free TrialLog in
Avatar of stanleyhuen
stanleyhuen

asked on

textfield validation

in a textfield, how can I validate a user fill in digits, charactors, "(", ")", and "-", not all other special symbols?

Thank you.
Avatar of tinchos
tinchos

what you can do is accept the text entered and after that parse the string to see if there are invalid characters
Avatar of Mick Barry
Use a custom Document as discussed in your previous question.
Ya, custom document will cater you needs. In the insert string method, you can do the validations by checking the input string.

Siva
How about this:

field.addKeyListener(new KeyAdapter() {
   public void keyPressed(KeyEvent e) {

      char c= e.getKeyChar();

      if (!isOK(c))              
         e.consume();
   }
});

Your function 'isOK()' checks whether or not character 'c' is acceptible.

kind regards
KeyListener won't work if you paste text into the field.
ksivananth, please do not repeat other peoples answers - it does neither the questioner nor you any good.
obejcts wrote: KeyListener won't work if you paste text into the field.

Ah, yes you're right, but together with the KeyEventListener (see my previous reply), a simple TextEventListener would do the job: the KeyEventListener controls the keystrokes while the TextEventListener would control the characters currently present in the TextField.

kind regards
stanleyhuen, exactly the same principle applies to limiting which characters are input as to how many are input, i.e. using a custom document in the input field. objects has already answered that at https://www.experts-exchange.com/questions/20507874/Can-I-limit-the-length-of-String-in-a-cell-of-a-JTable.html, which you should now accept and close, in addition to this one.
Oops, I didn't realize that the OP was asking similar questions. objects' answer is way more elegant than my quick hack; I'll refrain from further discussion in this topic.

kind regards
Avatar of stanleyhuen

ASKER

Thanks all.

In fact, I think this question is different from that question (https://www.experts-exchange.com/questions/20507874/Can-I-limit-the-length-of-String-in-a-cell-of-a-JTable.html),
In this question, I just want to check only digits, charactors and "(", ")" and "_" in a String, if there are other special charactors, eg, &, $, %, ^ or ! etc, then the method returns false.

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial