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

。_饼干妹妹 提交于 2019-11-30 06:17:38

问题


The required attribute in HTML5 is very handy:

<input type="text" required>

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


回答1:


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.

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

<input required pattern="\S+" title="This field is required">



回答2:


Try the pattern attribute. You'll need a regex which specifies 'at least one character'.




回答3:


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.*">


来源:https://stackoverflow.com/questions/13766015/is-it-possible-to-configure-a-required-field-to-ignore-white-space

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