将掩码应用于输入

Apply mask to input

我需要一个格式为 dddd-ddd(葡萄牙邮政编码)的输入掩码,我不想只为这个输入导入一个库.

这是我现在拥有的:

new Vue({
  el: '#app',
  data: {
    zip_code: '2770-315'
  },
  computed: {
    mask_zip_code: {
      get: function() {
        return this.zip_code;
      },
      set: function(input) {
        input = input.replace(/[^0-9-]/g, "");
       if(input.length >= 4) {
           input = input.substr(0, 4)+'-'+input.substr(5); // in case people type "-"
        }
        this.zip_code = input;
      }
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <input v-model="mask_zip_code" maxlength="8">
</div>

你有没有看到这个行为有点奇怪,它也允许输入字母。

尝试将 pattern 属性与正则表达式一起使用:

<script src="https://unpkg.com/vue"></script>
<form>
  <input v-model="mask_zip_code" pattern="[0-9]{4}-[0-9]{3}">
  <button>Submit</button>
</form>

这应该可以防止用户使用有效的葡萄牙邮政编码以外的任何内容提交表单。

我已经更新了您的代码段以使其按预期工作。 computed 值有效,但不会反映在输入中,这里使用一种方法更合适

new Vue({
    el: '#app',
    data: {
        zip_code: '2770-315'
    },
    methods: {
    mask_zip: function(event) {
        if (event.key && event.key.match(/[a-zA-Z]/)) {
           event.preventDefault()
        } else {
            if(this.zip_code.length >= 4) {
                this.zip_code = this.zip_code.substr(0, 4)+'-'+this.zip_code.substr(5); // in case people type "-"
            }
        }
        return this.zip_code;
    }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <input v-model="mask_zip_code" maxlength="8" @keypress="inputValidation">
  {{mask_zip_code}}
</div>