zoukankan      html  css  js  c++  java
  • vue开发中利用正则限制input框的输入(手机号、非0开头的正整数等)

    我们在前端开发中经常会碰到类似手机号输入获取验证码的情况,通常情况下手机号的输入需要只能输入11位的整数数字、并且需要过滤掉一些明显不符合手机号格式的输入,那么我们就需要用户在输入的时候就控制可以输入到输入框的字符。例如,首个字符是0或者非数字字符即使编辑了也输入不进去。这种需要通常就需要在input事件触发时就利用正则验证来实现了。以手机号为例:

    html

    <div class="e">
        <label>手机号</label>
        <input class="txt phonenum" maxlength="11" type="text" id="phonenum" v-model="phone" @input="inputPhone" placeholder="请输入手机号">
        <p class="err" id="err_phonenum" v-show="phoneerrmsg"><span>{{phoneerrmsg}}</span></p>
    </div>
    

    js

    //input事件处理
    inputPhone(e){
        this.phoneerrmsg = '';   //验证输入的提示信息
        let filtered = e.target.value.replace(/^0|[^d]/g, '');  
        if(this.phone != filtered){
            this.phone = filtered;
        }
        console.log(this.phone.length,this.phone,e)
    },
    
    //点击获取验证码的逻辑
    
    getCode(){
        //获取手机验证码
        let reg = /^1[3-9][0-9]{9}$/;  //以1开头第二位数字为3-9 的11位数字
        if(this.phone.length == 0){
            this.phoneerrmsg = '请输入手机号';
            return false;
        }else if(!reg.test(this.phone)){
            this.phoneerrmsg = '请输入正确的手机号';
            return false;
        }else{
            this.phoneerrmsg = '';
        }
        
        //获取验证码的逻辑省略。。。
    },
    

    补充点:
    在input事件中打印e时,会发现有时候事件对象中的isTrusted为false,这是因为Event.isTrusted返回一个布尔值,为true表明当前事件是由用户行为触发(比如说真实的鼠标点击触发一个click事件), 为false表明事件由一个脚本生成的(使用事件构造方法,比如event.initEvent)

  • 相关阅读:
    面向对象上
    面向对象下
    java大话设计模式
    《人体使用手册》阅读摘录
    mosquitto——一个开源的mqtt代理
    mosquitto0.15libmosquitto.c源码分析
    mosquitto0.15clientpub_client.c源码分析
    mosquitto0.15clientsub_client.c源码分析
    厦门三天游如何安排
    mimics教程中文版——第二章
  • 原文地址:https://www.cnblogs.com/csuwujing/p/11940282.html
Copyright © 2011-2022 走看看