开发者

Alert user if the password field contains spaces at start or end of the string with javascript

开发者 https://www.devze.com 2023-01-15 05:35 出处:网络
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 开发者_Python百科allowed.

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 开发者_Python百科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.


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.


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.


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消