I'm validating user input from a form.
I parse the input with NumberFormat
, but it is evil and allow almost anything. Is there any way to parse number more strict?
E.g. I would like to not allow these three inputs, for an integer, but Numberformat
allow all of them:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setParseIntegerOnly(true);
Number numberA = nf.parse("99.731"); // 99 (not what the user expect)
Number numberB = nf.parse("99s.231"); // 99 (invalid)
Number numberC = nf.parse("9g9"); // 9 (invalid)
System.out.println(numberA.toString());
System.out.println(numberB.toString());
System.out.println(numberC.toString());
text. NumberFormat is not thread safe.
NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are. NumberFormat helps you to format and parse numbers for any locale.
To format a number for the current Locale, use one of the factory class methods: myString = NumberFormat. getInstance(). format(myNumber);
Maybe this helps:
String value = "number_to_be_parsed".trim();
NumberFormat formatter = NumberFormat.getNumberInstance();
ParsePosition pos = new ParsePosition(0);
Number parsed = formatter.parse(value, pos);
if (pos.getIndex() != value.length() || pos.getErrorIndex() != -1) {
throw new RuntimeException("my error description");
}
(Thanks to Strict number parsing at mynetgear.net)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With