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)
本文转载自: https://www.cnblogs.com/csuwujing/p/11940282.html
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/vue-js/16192.html