File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Validating Strings in JTextFields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Validating Strings in JTextFields" Watch "Validating Strings in JTextFields" New topic

Validating Strings in JTextFields

Paul Statham
Ranch Hand

Joined: Dec 05, 2008
Posts: 55
Hi Folks,

I've created a class which allows me to validate strings being entered into a JTextField, I've extended javax.swing.text.PlainDocument. And now I can create a JTextField like so

This basically restricts what characters and how many of them can be entered into the text field. I.e. the validatorString only contains digits, if the user tries to enter any other character it won't let them.

Now I'd like to try and extend this functionality to allow users to enter a time. So my _validatorString currently reads "0123456789:". Of course this doesn't stop the user from entering a stupid time like 25:00,:2500,25:79 etc. etc.

Any ideas how I can restrict the user to only entering in the format

00-23 : 00-59

Thanks in advance,
John de Michele

Joined: Mar 09, 2009
Posts: 600

A regex is probably what you're looking for.

Rob Spoor

Joined: Oct 27, 2005
Posts: 19908

Just keep in mind that the user will not always have a complete string typed in. Perhaps you can auto-complete it for him:

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Validating Strings in JTextFields