Is there a way to create a textbox [input] that only accepts numbers for the code? Specifically, a phone number input that does not allow characters.
To ensure only numeric characters are accepted, we need to make adjustments to the acceptNumber()
method's complex string manipulation process.
A helpful approach when dealing with complicated string manipulations is to break down the process into manageable sections.
The following code snippet demonstrates this concept:
var x =this.value.replace(/\D/g,'').match(/(\d{0,3})(\d{0,3})(\d{0,4})/;
this.value=!x[2]?x[1]:'('+x[1]+')'+x[2]+(x[3]?'-'+x[3]:'');
This can be simplified into step-by-step instructions:
let thisValue = '(123) 456-7890';
let x = thisValue.replace(/\D/g,'');
console.log(`x: "${x}"`);
x = x.match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
console.log('x.match:', JSON.stringify(x));
thisValue = !x[2]
? x[1]
:'(' + x[1] + ')' + x[2] +
(x[3] ? '-' + x[3] : '');
console.log(`thisValue: "${thisValue}"`);
By utilizing the first item of the x
array, which contains just the digits, we can fulfill the request from the user:
this.value = x[0]; // "1234567890"
Below is a refined version of the original code incorporating the above modification. It effectively filters out any non-numeric characters as they are entered.
const app = new Vue({
el: '#app',
data: {
value: '',
maxmobile: 10
},
methods: {
acceptNumber() {
const x = this.value.replace(/\D/g, '');
console.log('this.value:', this.value, 'x:', x);
this.value = x;
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<form>
<input placeholder="Enter your mobile number" :maxlength="maxmobile" v-model="value" @input="acceptNumber" />
<button type="submit">Submit</button>
</form>
</div>