问题描述
我无法将上的文字输入限制为数字。根据,[d]或[0-9]应该这样做。但是,在
< input dir =ltrtype =texttitle =仅输入数字。 pattern =[\d] {9}id =uidname =1placeholder =Enter UIDrequired ='required'class =required placeholderminlength =9maxlength =9 autocomplete =off/>
它不适用于我(在任何浏览器中)。我必须添加js验证,例如以下内容(基于):
HTML:
onkeypress ='return isNumberKey(event)'
函数isNumberKey(evt){
var charCode =(evt.which)? evt.which:event.keyCode
if(charCode> 31&&(charCode< 48 || charCode> 57))
return false;
返回true;
}
我主要想知道是否有方法可以将pattern属性工作。但也可以随意评论我是否使用最佳做法路线。我不想使用HTML5 < input type =number/>
,因为它还没有广泛支持。
oninvalid
事件,当提交过程中验证失败时会被调用。 另外,你也可以还可以使用CSS选择器:有效
和:无效
来提供即时视觉反馈。 小提琴同时演奏(基于杰里的小提琴):
< form onsubmit =alert('submitted');> ;
< input type =submitvalue =Submit/>
< / form>
请注意,任何客户端验证只能用于快速反馈以改善用户体验。实际的验证应该始终在服务器端完成,因为客户端验证很容易被骗。
I can't get the pattern attribute on a text input to be limited to numbers. According to the javascript regular expressions list, [d] or [0-9] should do it. But in
<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):
HTML:
onkeypress='return isNumberKey(event)'
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.
The validation for the pattern
attribute will not prevent writing incorrect information into the field, but it will prevent submitting the form. The element also has an oninvalid
event that will be called when the validation fails during the submit.
Alternatively, you can also use the CSS selectors :valid
and :invalid
to provide instant visual feedback.
Fiddle showing both (based on Jerry's fiddle from the comments): 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.
这篇关于为什么输入模式属性不适用于数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!