views:

75

answers:

2

I am using the LiveValidation library found at www.livevalidation.com to handle client-side validation. One of the functions is to test for a regular expression. The example they provide on the site is to check if the phrase 'live' is within the a sentence. The code for that is:

var f2 = new LiveValidation('f2');
f2.add( Validate.Format, { pattern: /live/i } );

What would the regular expression be if I wanted to ensure that what was entered was between 7 and 16 characters and containted at least 1 numeric?

+1  A: 

You could use a lookahead assertion:

/^(?=.{7,16}$)\D*\d/
/^(?=\D*\d).{7,16}$/
Gumbo
Thanks! Regular expressions are a little confusing to me, lol. Can you explain yours and what is lookahead assertion? Thanks again.
Xaisoft
I found this one from Regular Expression library and it appears to work, just don't know if it is overkill./^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,16}$/
Xaisoft
@Xaisoft: Please read http://www.regular-expressions.info/lookaround.html#lookahead for an explanation of what a lookahead assertion is.
Gumbo
What if I don't want the password to start with a number?
Xaisoft
@Xaisoft: `/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{7,16}$/` tests for digits (`\d`), lowercase letters (`[a-z]`) and uppercase letters (`[A-Z]`). It’s very similar to mine (just `.*` instead of a negated character class).
Gumbo
@Xaisoft: `\d` (digit characters) is the complement to `\D` (anything but digit characters). If you don’t want to allow digits at the start, use `\D+` instead of `\D*` like I did (`*` = zero or more; `+` = one or more).
Gumbo
+1  A: 

This is a situation where, imo, 2 is better than one

var f2 = new LiveValidation('f2');
f13.add( Validate.Length, { minimum: 7, maximum: 16 } );
f2.add( Validate.Format, { pattern: /\d/ } );
Paul Creasey
Paul, can you explain why 2 is better than 1 in this case?
Xaisoft
You should add marks for the start and the end of the string. Otherwise the upper bound is not ensured.
Gumbo
@Gumbo, you are right, i've edited@Xaisoft, those 2 simple valiations are a lot easier to read and maintain, i'd wager it's faster too.
Paul Creasey
I use Validate.Length instead in the end!
Paul Creasey