• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Validate Numeric User Input

 
dave taubler
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to do something that I thought would be common and trivial, but after hours of googling, appears to be neither. Basically, I am simply trying to determine whether a given String represents a valid integer (or decimal, in some cases) for a given locale.

First, I checked simply to see if methods like Integer.parseInt() accept a Locale; they do not. Then, I thought I could retrieve the decimal-separator and group-separator (e.g. a comma--as in 1,000--in the US) from either the Locale or the NumberFormat object and do my own validation of the String, but I cannot retrieve that information either. So finally I decided to try a brute force approach just try to parse the String and if it works, the String is valid, and if an Exception is thrown, it is not valid:



But it turns out that you can pass pretty much any String in, and the NumberFormat will force it into a number. Seriously, "1asdsad" successfully converts to 1.

My last option, I guess, is to simply parse the String and validate that every character is either a number, or '.', '\'', ' ', or ','. But that hardly seems accurate, and would cause a lot of false negatives. So I think I must be missing something. What I'm trying to do has got to be commonplace, but I can't find any examples anywhere.

Does anyone know of a proper approach?

Thanks in advance.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dave,

You're really close. You can use the version of NumberFormat.parse() which takes a ParsePosition as the second argument. When parse() returns, check to see if theParsePosition.getIndex() == theString.length(); if it is, the parse accepted all the characters.
 
dave taubler
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest,

Thanks so much for your response. I did a quick check, and it seems indeed this will solve my issue.

Best regards,
Dave
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic