Search code examples
javaregexswingjtextfield

Swing JTextField - Max 3 digits before decimal and max 2 digits after decimal


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.


Solution

  • 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.