简体   繁体   中英

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:

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

How can I achieve what I want with html5?

So you can totally do that by adding type="number" to your input field, It'll work in most browsers .

I'd recommend using sort of regex and a bit of JS to evaluate the input and then replace the input with permitted characters.

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.

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). But since you are already using js, you can just do it with for example the jQuery.keypress() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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