4 digits of js mobile phone number display space and every 4 digits of bank card display space effect

  • 2021-08-05 08:56:19
  • OfStack

Sometimes, the development will encounter the input of mobile phone number and bank card number. According to the demand of displaying one space every four digits, it is convenient for users to read. If it is pure display, it is easy to realize. If it is one side input and one side display, it is a bit difficult

Some people use two input to realize, one is responsible for inputting data, but it is transparent and invisible, and the other one is displayed on the interface, which solves this requirement in disguise (numeric keypad can be called on mobile phone)

This time to write an demo, only one input timer with constant query input characters to judge the input data (can not directly call the numeric keypad, because there are spaces inside)

If it is a bank card number, change the character judgment length to, and you can also judge the length according to the actual demand

lastLen === 5 || lastLen === 10 || lastLen === 15|| lastLen === 20

Don't say much, put on the code


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 <meta name="renderer" content="webkit">
 <title>Title</title>
</head>
<body>
<input type="text" id="telphone"><span id="err"></span>
<script>
 var telphone = document.getElementById('telphone');
 var err = document.getElementById('err');
 // Define two cache values 
 var firstLen = 0;
 var lastLen = 0;
 var re=/^1(3|4|5|7|8)\d{9}$/;
 telphone.oninput = function () {
  telphone.value = telphone.value.substr(0, 13);// Enter only 11 Bit +2 Spaces 
  // User input full 11 Bit start validation 
  if(telphone.value.length==13){
   // Validate after removing spaces from data 
   if(!re.test(telphone.value.replace(/\s/g, ''))){
    err.innerHTML=' Wrong mobile phone number '
   } else{
    err.innerHTML=''
   }
  }else{
   err.innerHTML=''
  }

 }
 telphone.onfocus = function () {
  timer = setInterval(function () {
   lastLen = telphone.value.length;
   if (lastLen > firstLen) {
    firstLen = telphone.value.length;
    if (lastLen === 4 || lastLen === 9) {
     var temp1 = telphone.value.substr(0, telphone.value.length - 1);
     var temp2 = telphone.value.substr(telphone.value.length - 1);
     telphone.value = temp1 + ' ' + temp2;
    }
   } else if (lastLen <= firstLen) {
    if (lastLen === 4 || lastLen === 9) {
     telphone.value = telphone.value.substr(0, telphone.value.length - 1);
    }
    firstLen = telphone.value.length;
   }
  }, 10);// If the mobile phone is stuck, you can increase the timer time appropriately 
 }
</script>
</body>
</html>

Related articles: