Reputation: 2647
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.
Upvotes: 1
Views: 1923
Reputation: 4650
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.
Upvotes: 1
Reputation: 75844
Where password
is the string value of your candidiate:
if(password.match(/^\s|\s$/))
{
// failed
}
In the regex:
Upvotes: 0
Reputation: 887469
Like this:
if (/^\s|\s$/.test(str)) {
//Waah waah waah!
}
Explanation:
/.../
expression creates a RegExp object..test()
method checks whether the given string matches the regex.|
expression in the regex matches either whatever is before it or whatever is after it (an or
expression)\s
expression matches any single whitespace character (such as a space, tab, or newline, or a fancy unicode space)^
character matches the beginning of the string$
character matches the end of the stringThus, the regex reads: Match either the beginning of the string followed by whitespace or whitespace followed by the end of the string.
Upvotes: 3