2

I have very strange issue.

in a very sample search form with one input field:

 <input pattern="\S.{3,}"  name="text"/>

The validation fails for value

     dds sdsd
, but JS says it's Ok.

/\S.{3,}/.test('     dds sdsd')
true
/\S.{3,}/.test('    ')
false

Maybe I am missing something small or pattern is wrong, but according to regex.com it should be valid.
The idea is to prevent submit empty spaces. I am searching for a solution without write JS code.

<form method="GET" action="/">
<input class="form-control" name="text" type="text" pattern="\S.{3,}"  />
<input type="submit" value="search" >
</form>

1
  • you have a typo error in your first example (parttern) Commented Apr 21, 2017 at 22:07

1 Answer 1

5

The HTML5 pattern is anchored by default, ^(?: and )$ are added at the start/end of the pattern when it is passed JS regex engine.

You need to use

<input pattern=".*\S.{3,}.*"  name="text"/>

to make it work the same way as in JS with RegExp#test.

However, to require at least 1 non-whitespace char in the input, I'd recommend using

<input pattern="\s*\S.*"  name="text"/>

See this regex demo. It will match 0+ whitespace chars at the start of the string (\s*), then will match any non-whitespace char (\S) and then will grab any 0+ chars greedily up to the end of the input.

<form method="GET" action="/">
<input class="form-control" name="text" type="text" pattern="\s*\S.*" title="No whitespace-only input allowed."/>
<input type="submit" value="search" >
</form>

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks .*\S.{3,}.* does the trick . My target is to have at least 3 symbols in the input
Any 3 symbols? Or 3 consecutive non-whitespace symbols? Or 3 non-whitespace symbols anywhere in the string? Please let know of actual requirements, since \S.{3,} looks strange: a non-whitespace char followed with any 3 or more chars.
Yeah it's strange. If I have leading spaces but there are ' a a' in the string it should match. I mean something like trim start and end. The best for now is .*\S.{1,}\S
Ok, if you plan to require at least 3 non-whitespace symbols, use pattern="(?:\s*\S){3}.*". To match at least 3 consecutive non-whitespace symbols in a string, use pattern=".*\S{3}.*". Feel free to drop a comment in case you need more help with it.
The space between letters is correct. Only spaces at the start and the end should be ignored. I think, the pattern from previous comment works. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.