手机号自动补空格

pc端通过keyup事件做处理:注意添加maxlength="13"

      

      

 

  $('#m-input').on('keyup', function () {
    var that = $(this);
    var value = that.val();
    value = value.replace(/[^0-9]/ig, ""); 
    var arr = value.split('');
    if (arr.length >= 4) {
      arr.splice(3, 0, ' ');
    } 
    if (arr.length >= 9) {
      arr.splice(8, 0, ' ');
    }
    value = arr.join('');
    that.val(value);
  });
  $('#m-search-btn').on('click', function () {
    var value = $('#m-input').val();
    value = value.replace(/[^0-9]/ig, ""); 
    console.log(value);
  })

 

手机端不支持keyup事件。采用input事件处理、先验证是否有汉字。否则

    validatePhone(){

            var pattern = new RegExp("[\u4E00-\u9FA5]+");

            if(pattern.test(this.phone)){

               this.phone=''

               this.disabled=true

                return

            }else{

                this.phone= this.phone.replace(/(\d{3})(\d{4})/,"$1 $2 ")

                let val= this.phone.replace(/\s+/g,"");

                if(val.length==11){

                    this.disabled=false

                    if(checkPhone(val)){

                        ajax(...)

                    }else{

                        this.$toast("手机号格式有误")

                    }

                }else{

                    this.disabled=true

                }

            }

        },

也可以采用第二种方法:

  function formatPhoneOnkeyUp(mobile){

                var value = mobile.replace(/\D/g, '').substring(0, 11);

                var valueLen = value.length;

                if (valueLen > 3 && valueLen < 8) {

                    value = `${value.substr(0, 3)} ${value.substr(3)}`;

                } else if (valueLen >= 8) {

                    value = `${value.substr(0, 3)} ${value.substr(3, 4)} ${value.substr(7)}`;

                }

                return value;

    }

你可能感兴趣的:(javascript)