tags:

views:

46

answers:

3

Hi,

I have a password field, and if password contains any spaces at start or end, I would like to alert the user. password can be a phrase so spaces in between the string is allowed.

I am sure it can be done through regex, but I don't have much hands on it.

If some one can please help me out.

Thanks, Tanmay

+2  A: 

Like this:

if (/^\s|\s$/.test(str)) {
    //Waah waah waah!
}

Explanation:

  • The /.../ expression creates a RegExp object.
  • The .test() method checks whether the given string matches the regex.

  • The | expression in the regex matches either whatever is before it or whatever is after it (an or expression)
  • The \s expression matches any single whitespace character (such as a space, tab, or newline, or a fancy unicode space)
  • The ^ character matches the beginning of the string
  • The $ character matches the end of the string

Thus, the regex reads: Match either the beginning of the string followed by whitespace or whitespace followed by the end of the string.

SLaks
Perfect. May be i'll start playing around the regex bit more now.Thanks :)
jtanmay
A: 

Where password is the string value of your candidiate:

if(password.match(/^\s|\s$/))
{
  // failed
}

In the regex:

  • ^ means "start of line"
  • \s means "a whitespace character"
  • | means OR
  • $ means "end of line"
annakata
*regex.test(str)* is more appropriate than *string.match(reg)* when looking for a true or false response from a regex. See SLaks' answer.
Andy E
Meh, semantically it's still clear, performance wise it's effectively identicial. `match` has broader application than `test` and I tend to prefere reducing the patterns used where possible.
annakata
+1  A: 

It's easy to write a regular expression to test whether there is whitespace before or after the text; anchor the test with ^ and $.

/^\s|\s$/

But why even bother the user with it? I think it would be better to trim the whitespace automatically.

str.replace(/^\s+|\s+$/g, '');

No muss, no fuss.

Timothy
The OP is talking about a password input - it's not the sort of thing you would want to change the value of, it could be very confusing for the user.
Andy E
how so? If used properly, the value of the password should never matter, rather the hash value of it does. So if you're doing the same transforms everywhere, the user does not need to be aware of them.
Timothy
@timothy, yes I do agree with your view but in my case I have to use a webservice for checking user credentials, and unfortunately webservice is trimming all the data sent to it! So I need to alert user for this. And yes I would be trimming the vales later.
jtanmay