File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes form field validation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "form field validation" Watch "form field validation" New topic

form field validation

Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126
I have a small problem. I have a form that is taking in a credit card number. The servlet that the form is posted to is to check the credit card number for two things:

1. to make sure it's at least 15 digits for american express and maximum 16 for visa and mastercard.

2. make sure the field was not left blank.

I have the first task done. But I'm unsure how to ensure the field isn't left blank.

My servlet reads in the value from the form as follows:
long cardnumber = Long.parseLong(request.getParameter("ccnumber"));

How can I check if the field is left blank, which gives the result "".

P.s. I know I could use javascript on the jsp page to ensure a value is entered before the form can be submitted, but I'd rather not if possible.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Look at the string version of the value before you try parsing it to a Long.

String value = request.getParameter("ccnumber");

Play with entering nothing, entering something and deleting it with backspace, delete with the delete key, any other combination you can think of. I think sometimes you'll find null and sometimes an empty string. At least our web folks always test for both.

Alternatively you might just catch the exception thrown by parseLong for invalid values like embedded spaces or letters or whatever. Try that with those input combinations, too.
[ April 19, 2005: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126
Ah yes, that's brilliant, I don't know why I didn't think of that before. Thanks so much!
I agree. Here's the link:
subject: form field validation
It's not a secret anymore!