• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Validate the password

 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic