【问题标题】:Regex input formatting with vue.js使用 vue.js 进行正则表达式输入格式化
【发布时间】:2019-10-25 17:06:25
【问题描述】:

我正在尝试在 vue.js 中格式化用户输入。输入代表时间 mm.ss。然后是两个数字,然后是两个数字。输入前两个数字后,点应自动出现。我能够使用 rexeg 来实现它,这是 codepen:

https://codepen.io/Marek92/pen/KKKqKjx

<div id="app">
  <h1>{{ title }}</h1>

  <input type="text" v-model="performance">
</div>
new Vue({
  el: '#app',
  data: {
    title: 'Input formating!',
    performance: '12.00'
  },

  watch: {
            performance() {
                this.performance = this.performance.replace(/[^0-9]/g, '')
                    .replace(/^(\d{2})(\d{2})?/g, '$1.$2')
                    .substr(0, 5);
            }
        }
});

但是问题在于输入是否存在。假设“12.00”,您从最后开始使用退格键删除数字。你被困在这个点上。无法删除点,这是我的问题。如何更改正则表达式以删除点?还是其他解决方案?

【问题讨论】:

    标签: regex vue.js input-field


    【解决方案1】:

    请看下面的代码-

    new Vue({
      el: '#app',
      data: {
        title: 'Input formating!',
        performance: '12.00'
      },
    
      watch: {
                performance() {
                     var a = this.performance.replace(/[^0-9]/g, '')
                        .substr(0, 5);
                     if (a.length >= 3) {
                         a = a.substring(0, 2) + '.' + a.substring(2, a.length)
                     }
                     this.performance =a;     
                }
            }
    });
    

    说明:多于2位时,尽量在2位后加一个点。否则删除除数字以外的所有字符。

    https://codepen.io/ashfaq_haq/pen/xxxrbYO

    【讨论】:

    • 是的,但此解决方案不会在写入两位数后添加点。有没有办法同时保留?写完两位数后自动加点,去掉数字时不会卡在点上?
    【解决方案2】:

    我的 ESLint 构建规则不允许我使用 Regex。如果你有同样的问题,只需通过配置 eslintrc.js 文件删除规则

      'rules': {
        // allow regex test of phone numbers
        'no-useless-escape': 0
      }
    

    然后您可以创建 const 并使用测试方法。非常适合我的电话号码检查。

    const phoneNumberFormat =
    new RegExp(/^[+]?(\d{1,2})?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/)
    
    const validatePhoneNumber = (context, event) => {
      let address = context.address
      if (!phoneNumberFormat.test(address.phoneNumber)) {
        return false
      }
      return true
    }
    

    【讨论】:

      【解决方案3】:

      您的第二个捕获组是可选的,因此当您删除它时它会尝试添加.,因为两位数也与正则表达式匹配。一种选择是删除可选语法?,使用/^(\d{2})(\d{2})/g/^(\d{2})(\d{1,2})/g,以便仅在有两个以上数字时才开始格式化。

      https://codepen.io/leopsidom/pen/zYYzxKY

      【讨论】:

      • 是的,但此解决方案不会在写入两位数后添加点。有没有办法同时保留?写完两位数后自动加点,去掉数字时不会卡在点上?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2019-09-15
      • 2020-09-14
      相关资源
      最近更新 更多