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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:15:26  来源:igfitidea点击:

Is it possible to configure a required field to ignore white space?

htmlrequired-field

提问by Benjamin

The requiredattribute in HTML5 is very handy:

HTML5 中的required属性非常方便:

<input type="text" required>

But it still allows users to enter white space only. Is there an HTML-only solution to this?

但它仍然只允许用户输入空白。是否有仅 HTML 的解决方案?

回答by James Messinger

Use the patternattribute combined with the requiredattribute. And be sure to include a titleattribute 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 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.*">