How do I use an <input>'s pattern attribute to require at least one usable character?

好久不见. 提交于 2020-02-01 08:58:50

问题


I've got an <input> searchbox, and I want to add pattern to guide the user to submitting more than just whitespace. The required attribute doesn't let them submit an empty string, but searching for a couple of spaces goes through and isn't useful.

I've tried the following, but input such as "a couple of keywords" isn't valid with them:

  • pattern="\S+"
  • pattern="(!\s*)"
  • pattern="(\s*\S\s*){,}"

I know the ^ and $ symbols are implied, and adding them doesn't change anything in the results.

How do I write a pattern that matches every input except white space without any other characters?


回答1:


You could try the below regexes.

pattern = ".*\S.*"

or

pattern = ".*[^ ].*" 

So this regex asserts that there must be atleast one non-space character present in the input string. .* matches any character zero or more times. [^ ] negated character class which matches any character but not of a space. Since [^ ] matches also a tab character, adding also the tab character [^ \t] inside the char class would be better.



来源:https://stackoverflow.com/questions/29112549/how-do-i-use-an-inputs-pattern-attribute-to-require-at-least-one-usable-chara

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!