I want to validate forms as shown in the Java Developers Almanac example. My problem is when I use beans with numeric values such as int. If I submit the form with String values in the int field, the page throws NumberFormatException. My validation code is never reached. What do I need to do to perform my own validation?
Originally posted by Ben Souther: Integer.parseInt(yourString) will convert a String to an int (providing the string you pass to it can be converted to an int .
if can not be converted into String, he will again run into problem. Use some utility method of your own. like below,
It is returning Integer, instead of int. Actually I prefer to use Integer when writing VOs. Because there is a lot difference between 0 and null according the the database especially. If you want to write your VO into database you wouldn't want to write null as 0. and int can not be a null.
No, there's no need to change your data type. If your user is passing non-numerics in, you want to catch that right up front.
Java now (starting with version 1.4) has regular expression tools. You could also write a quick isInt(String) method using those.
Joined: Aug 15, 2004
Yeah this sounds better. Actually, I was not really saying to change the type . However, I explained the case, why change to Integer.
Joined: Apr 02, 2003
The error shown in the stacktrace is caused by the line, . The tag reads the form and populates the bean. If the form field contains a String and the bean field is an int, the NumberFormatException is thrown. If my jsp form bean can only use Strings, then the usefulness of setting all properties with "*" is dimminished. Is there a way to catch bad input data using this example? I understand the suggestions posted, but, how can they be applied since the jsp:setProperty tag is causing the problem before I can run my error checking code?
These are just a couple ideas. Not sure the second one will even compile. I generally handle all the validation and transformation in servlets so I'm interested in seeing if someone has a more graceful or "established best practice" way of doing this. [ January 13, 2005: Message edited by: Ben Souther ]