Search code examples
javaswingvalidationdoublejtextfield

How to validate jtextfield which accepts only float/decimal value in java swing?


I am trying to validate text field such that it accepts float or double values like .25, 0.2, 111.25
It should not accepts values like ...25, 0.2.2. etc


Solution

  • -?(\d*\.)?\d+([eE][+\-]?\d+)?|[nN]a[nN]|[iI]nf(inity)? is the regex I usually use for parsing doubles.

    If you don't want infinities and NaNs,

    -?(\d*\.)?\d+([eE][+\-]?\d+)?

    If you also don't want exponential notation,

    -?(\d*\.)?\d+

    And don't forget to escape backslashes if you need to.