简体   繁体   中英

HTML input pattern not working validation

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM