Html 为什么输入模式属性不适用于数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19066674/
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 13:53:41  来源:igfitidea点击:

Why is input pattern attribute not working for numerics?

javascripthtmlregex

提问by levininja

I can't get the pattern attributeon a text input to be limited to numbers. According to the javascript regular expressions list, [d] or [0-9] should do it. But in

我无法将文本输入的模式属性限制为数字。根据javascript正则表达式列表, [d] 或 [0-9] 应该这样做。但在

<input dir="ltr" type="text" title="Enter numbers only." pattern="[\d]{9}" id="uid" name="1" placeholder="Enter UID" required="'required'" class="required placeholder" minlength="9" maxlength="9" autocomplete="off" />

it doesn't work for me (in any browsers). I have to add js validation such as the following (decided to go this route for simplicity based on this post):

它对我不起作用(在任何浏览器中)。我要补充JS验证,如下面的(决定去基于对这种简单的路线这篇文章):

HTML:

HTML:

onkeypress='return isNumberKey(event)' 

js:

js:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

I mainly want to know if there's a way I can get the pattern attribute to work. But also feel free to comment on whether I'm using best practices route for this. I don't want to use HTML5 <input type="number"/>as it's not widely supported enough yet.

我主要想知道是否有办法让模式属性起作用。但也可以随意评论我是否为此使用了最佳实践路线。我不想使用 HTML5,<input type="number"/>因为它还没有得到足够的广泛支持。

回答by Ingo Bürk

The validation for the patternattribute will not prevent writing incorrect information into the field, but it will prevent submitting the form. The element also has an oninvalidevent that will be called when the validation fails during the submit.

pattern属性验证不会阻止将错误信息写入字段,但会阻止提交表单。该元素还有一个oninvalid事件,在提交期间验证失败时将调用该事件。

Alternatively, you can also use the CSS selectors :validand :invalidto provide instant visual feedback.

或者,您也可以使用 CSS 选择器:valid:invalid提供即时的视觉反馈。

Fiddle showing both (based on Jerry's fiddle from the comments): http://jsfiddle.net/bHWcu/1/

小提琴显示两者(基于评论中杰瑞的小提琴):http: //jsfiddle.net/bHWcu/1/

<form onsubmit="alert('Submitted');">
    <input dir="ltr" type="text" title="Enter numbers only." pattern="[\d]{9}" id="uid" name="1" placeholder="Enter UID" required="'required'" class="required placeholder" maxlength="9" autocomplete="off" />
    <input type="submit" value="Submit" />
</form>

Note that any client-side validation should only be used for fast feedback to improve the user experience. The actual validation should always be done server-side, as the client-side validation can easily be cheated.

请注意,任何客户端验证都应仅用于快速反馈以改善用户体验。实际验证应始终在服务器端完成,因为客户端验证很容易被欺骗。