Reputation: 573
I need a mask for input that needs to have the format of dddd-ddd (Portuguse zip code), I don't feel like importing a library just for this input.
This is what I have right now:
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>
Has you can see the behavior is a little wierd and it allows to type letters as well.
Upvotes: 0
Views: 1337
Reputation: 1288
I've updated your snippet to work as you intended it. The computed
value works but it will not be reflected in the input, instead a method is more appropriate here
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>
Upvotes: 1
Reputation: 522151
Try using the pattern
attribute with a regex:
<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>
This should prevent users from submitting the form with anything other than a valid Portuguese zip code.
Upvotes: 0