This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 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: 56
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: 20136

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
It's not a secret anymore!