我需要一个掩码,其输入格式必须为 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>
您是否可以看到该行为有点奇怪,并且还可以键入字母。
答案 0 :(得分:1)
我已经更新了您的代码段,使其可以按预期工作。 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>
答案 1 :(得分:0)
尝试将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>
这应防止用户使用有效的葡萄牙邮政编码以外的任何形式提交表单。