1

I would like to allow all special characters and white space in between words only for a password input field.

If whitespace entered at the leading, trailing of string, regex should fail

Any useful javascript regex?

I tried \S this does not accept any white space, would that be sufficient?

I tried \A\s|\s*\Z , but not able to negate this.

Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
Sri
  • 1,205
  • 2
  • 21
  • 52

3 Answers3

1

Using something like [^\s] would suffice.

Drewness
  • 5,004
  • 4
  • 32
  • 50
1

The \A (start of string) and \Z (end of string) anchors are not supported by JS RegExp. If you use /\S/ it will only match any non-whitespace char, anywhere inside a string. If you use /^\s|\s*$/ it will match a whitespace at the start or any 0 or more whitespaces at the end.

You need

/^\S+(?:\s+\S+)*$/

See the regex demo.

It will match:

  • ^ - start of string
  • \S+ - 1 or more non-whitespace chars
  • (?:\s+\S+)* - any 0 or more occurrences of
    • \s+ - 1+ whitespaces
    • \S+ - 1+ non-whitespace chars
  • $ - end of string.

JS demo:

var strs = ['Abc 123 !@#', 'abc123@', '   abc34', ' a ', 'bvc   '];
var rx = /^\S+(?:\s+\S+)*$/;
for (var s of strs) {
  console.log("'"+s+"'", "=>", rx.test(s));
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1

I don't know if it's totally fine but in your case, I think this could apply better

^((\w)*){1}$

  • This does not allow any special characters and contains two completely superfluous capturing groups and one redundant quantifier (`{1}` is a no-op). – melpomene Feb 13 '18 at 22:17
  • You are right, I want to apologize @sri because I read something totally opposite to the question done. Next time I will read it carefully. – Antonio Rodriguez Feb 17 '18 at 23:22