简体   繁体   中英

How to restrict IMEI number to only 15 digits without counting space after 4 digits

I have input field for imei number which should take only 15 digits that should only be numbers. Which I have done, my code below takes only 15 digits and leaves a space after 4 digits.

But the main problem I am facing here is if you hold any number it will take 18 digits. because when we type fast it is couting spaces also. Here is fiddle link to try here

IMEI

$(".imei").on('keyup', function() {
  var foo = $(this).val().split(" ").join(""); 
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
  }
  $(this).val(foo);
});
$(".imei").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
             // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

Change keyup to keypress :

$(".imei").on('keypress', function() {

keyup will only fire when you let go of the key, while keypress will fire every time the key is sent to the input.

Keep the keydown code as it's used to limit what's allowed.

Updated fiddle: http://jsfiddle.net/1zLwgf66/1/


The problem with keypress is that it occurs before the key has been sent to the input. You can get around this by adding the key to the input before running your code, or waiting until the default code has completed, by adding a simple setTimeout. With setTimeout, you'll have closure issues, so you need to copy this :

$(".imei").on('keypress', function() {
  var inp = this;
    setTimeout(function() {
      var foo = $(inp).val().split(" ").join(""); 

Updated fiddle: http://jsfiddle.net/1zLwgf66/2/

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