简体   繁体   English

阻止用户使用HTML5在输入文本字段中输入非数字

[英]Preventing users from entering non-digits in input text field with HTML5

I have an input field of type text. 我有一个文本类型的输入字段。 Users should only be allowed to enter digits in the field. 只允许用户在字段中输入数字。 If they attempt to enter a non-digit, like a character, it should be ignored and not display in the field ( and not submitted to the server). 如果他们尝试输入非数字,如字符,则应忽略它并且不在字段中显示(并且不提交给服务器)。 I thought I could achieve this with the HTML5 pattern attribute: 我以为我可以用HTML5模式属性实现这个目的:

<input class="form-control" data-remote="true" data-url="/contacts" data-method="put" pattern="^[0-9]*$" type="text" value="123456" name="contact[phone]" id="contact_phone">

But it doesn't work as expected. 但它没有按预期工作。 I can still enter any character into the field. 我仍然可以在场上输入任何角色。 There is no form submit button here. 这里没有表单提交按钮。 As soon as they tab out of field, the ajax call is made. 一旦他们跳出字段,就会进行ajax调用。

How can I achieve what I want with html5? 如何用html5实现我想要的?

So you can totally do that by adding type="number" to your input field, It'll work in most browsers . 所以你可以通过在输入字段中添加type="number"来完全做到这一点, 它可以在大多数浏览器中使用

I'd recommend using sort of regex and a bit of JS to evaluate the input and then replace the input with permitted characters. 我建议使用一些正则表达式和一些JS来评估输入,然后用允许的字符替换输入。

var phone_input = document.getElementById('contact_phone');

function validDigits(n){
  return n.replace(/[^0-9]+/g, '');
}

phone_input.addEventListener('keyup', function(){
  var field = phone_input.value;
  phone_input.value = validDigits(field);
});

Here's a quick codepen 这是一个快速的代码

I'd also put a bit of validation on the model, just in case someone bypasses the JS. 我还对模型进行了一些验证,以防有人绕过JS。

I think it won't work with plain html5 since the pattern goes into affect after you submitted the form (It will make validation fail). 我认为它不适用于普通的html5,因为模式在你提交表单后生效(它会使验证失败)。 But since you are already using js, you can just do it with for example the jQuery.keypress() function. 但是因为你已经在使用js,所以你可以使用例如jQuery.keypress()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM