Html 是否可以配置必填字段以忽略空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13766015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to configure a required field to ignore white space?
提问by Benjamin
回答by James Messinger
Use the pattern
attribute combined with the required
attribute. And be sure to include a title
attribute as well, since most browsers insert the title text into the validation pop-up bubble.
将pattern
属性与属性结合使用required
。并且一定要包含一个title
属性,因为大多数浏览器将标题文本插入到验证弹出气泡中。
<input required pattern=".*\S+.*" title="This field is required">
The .*\S+.*
pattern requires at least one non-whitespace character, but also allows whitespace characters (spaces, tabs, carriage returns, etc.) at the beginning or end. If you don't want the user to be able to put whitespace at the beginning/end, then use this instead:
该.*\S+.*
模式至少需要一个非空白字符,但也允许在开头或结尾使用空白字符(空格、制表符、回车等)。如果您不希望用户能够在开头/结尾放置空格,请改用:
<input required pattern="\S+" title="This field is required">
回答by robertc
Try the pattern
attribute. You'll need a regex which specifies 'at least one character'.
试试pattern
属性。您将需要一个指定 '至少一个字符' 的正则表达式。
回答by Jeremy Moritz
You probably want this:
你可能想要这个:
<input type="text" required pattern="\S(.*\S)?">
(At least one non-whitespace character and no whitespace at the beginning or end of the input)
(输入的开头或结尾至少有一个非空白字符且没有空白字符)
Or if whitespace at the beginning and end are fine, then this:
或者,如果开头和结尾的空格都很好,那么这个:
<input type="text" required pattern=".*\S.*">