1

Can anyone help me with the validation for JTextField which can only allow up to 3 digits before the decimal and up to 2 digits after the decimal?

I used regex \\d{3}\\.\\d{2} for InputVerifier. This is allowing exactly 3 and 2 before and after decimal. I need <=3 and <=2 before and after decimal.

My project only needs JTextField.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Kaushi
  • 198
  • 3
  • 8
  • 20
  • Your tag list should include [tag:regex]. According to [this question](http://stackoverflow.com/questions/10771269/one-or-two-numeric-digits-regex), you can use `\d{1,2,3}.\d{1,2}`. – goncalotomas May 19 '15 at 09:35
  • Does `^\d{1,3}\.\d{1,2}$` work for you? It will require at least 1 digit on both sides of the decimal, and the first part can be 1 to 3 digits long, and the second can be 1 to 2 digits long. To allow `.2` like input, try `^\d{0,3}\.\d{1,2}$`. – Wiktor Stribiżew May 19 '15 at 10:08
  • *"My project only needs JTextField."* Why? In fact, this looks a lot like a case for `JFormattedTextField`. – Andrew Thompson May 19 '15 at 11:22
  • @stribizhev yes '^\d{0,3}\.\d{1,2}$' is working.... – Kaushi May 19 '15 at 11:32
  • @AndrewThompson as of now we are asked to use JTextField. So we are trrying to workout with it. – Kaushi May 19 '15 at 11:37

1 Answers1

2

To validate such strings, you can use the following regex:

^\d{0,3}\.\d{1,2}$

It will require at least 1 digit on the right side of the decimal, and the first part can be 0 to 3 digits long (due to {0,3} quantifier).

Note that it allows .2-like input.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • By using **InputVerifier**, after typing the 4th digit before the decimal and getting the return value from 'verify' method is false. But my query is like, i should not be able to type any digits after entering 3 digits before decimal. Same is the case also with the digits after the decimal. Is there any way for this?????? – Kaushi May 19 '15 at 11:43
  • You should check the official [InputVerifier documentation here](http://docs.oracle.com/javase/6/docs/api/javax/swing/InputVerifier.html). To set up this check, you need to set `tf1.setInputVerifier(new PassVerifier());` to the `JTextField` and inside `PassVerifier`, check `tf.getText()` against the regex. I hope it is clearer now. – Wiktor Stribiżew May 19 '15 at 11:57