Reputation: 127
I'm trying to limit the set of characters allowed in an inputfield of number type. The problem is that I can't find a way to "overwrite" the text in the inputfield to delete not valid characters.
Here is the code Im testing with:
<template>
<div>
<input @input="validate" :model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
</div>
</template>
<script>
export default {
data: () => ({
message: ""
}),
methods: {
validate(input){
// the regex is allowing only numbers and either a comma or a period
this.message = input.target.value.match(/[0-9]*(,|\.)?[0-9]*/gm)[0]
}
}
}
</script>
All characters in the inputfield stays the same, while the "message" variable is the parsed validated string. How do I get that "message" string into the inputfield?
Edit: here is a jsfiddle of the code above.
Upvotes: 0
Views: 58
Reputation: 9200
Well, :model
is a shorthand for v-bind:model
not to be confused with v-model
for Vue directive (we want this one). So do this:
<input @input="validate" v-model="message" placeholder="edit me">
However, I would suggest using Vue-Masked-Input component or vue-inputmask (my personal preference) for this purpose, as they help with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers, etc.
Upvotes: 1
Reputation: 1687
There is a method in vuejs called watch that allows you to watch for DOM changes. Also :model is not the shorthand for v-model.
:model = v-bind:model
Here is a jsfiddle to a working example. https://jsfiddle.net/awk7g2un/
Just replace my data with your parsed value
Upvotes: 1