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 Validate the password Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Validate the password" Watch "Validate the password" New topic

Validate the password

meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
Hi all....
I would like to know how to validate the password inside the service method.The password should contain both numeric as well as character and the length should be between 4 and 10.

Thanks in advance
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

This question would do better in Java Beginner.

If you're using 1.4 or higher, look at the regexp related methods of the String class.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
By "character" I assume you mean letters (lower- and uppercase), since Strings by definition only contain characters. Can it contain other characters (punctuation, accented letters, non-printables), or only alphanumeric ones? Must it contain both letters and numbers, or at least one of either?

To enforce a 4-10 character password containing only alphanumerics, but also one of each type, you'll need to use two regexp tests (off the top of my head): "[a-zA-Z0-9]{4,10}" and "(?:[a-zA-Z][0-9]|[0-9][a-zA-Z])".

The first one validates that the password contains 4-10 alphanumeric characters. You should use match() to compare the entire password to the pattern.

The second one is a bit tricky, and I haven't tested it. You should use find() to test whether or not the password contains the pattern somewhere. It checks that the password contains a letter followed by a digit or a digit followed by a letter. If the password contains at least one of each, it will pass.

If you can't or don't want to use regular expressions, this would be very easy to do in a loop.

Can anyone come up with a way to combine both tests in a single expression? I can only come up with one that doesn't enforce the length requirement: "[a-zA-Z0-9]*(?:[a-zA-Z][0-9]|[0-9][a-zA-Z])[a-zA-Z0-9]*". You could of course use length() for the last check.
I agree. Here's the link:
subject: Validate the password
jQuery in Action, 3rd edition