简体   繁体   English

HTML输入模式无法正常工作

[英]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. ,但JS说没关系。

 /\\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. 也许我缺少一些小东西或图案错误,但是根据regex.com,它应该是有效的。
The idea is to prevent submit empty spaces. 这样做的目的是防止提交空白空间。 I am searching for a solution without write JS code. 我正在寻找不编写JS代码的解决方案。

 <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. HTML5 pattern默认是锚定的,在传递JS regex引擎时,在模式的开始/结尾处添加^(?:)$

You need to use 您需要使用

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

to make it work the same way as in JS with RegExp#test . 以使其与使用RegExp#test JS中的工作方式相同。

However, to require at least 1 non-whitespace char in the input, I'd recommend using 但是,要在输入中至少包含1个非空白字符,我建议使用

<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. 它将在字符串的开头( \\s* )匹配0+个空白字符,然后将匹配任何非空白的char( \\S ),然后将贪婪地抓取任何0+字符直到输入的末尾。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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