Reputation: 820
methods: {
acceptNumber() {
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] : '');
}
<input class="input-section label-set"
type="text"
v-model.trim="$v.mobile.$model"
:class="{'is-invalid': validationStatus($v.mobile)}"
placeholder="Enter your mobile number"
:maxlength="maxmobile" v-model="value"
@input="acceptNumber"
/>
<div v-if="!$v.mobile.minLength"
class="invalid-feedback"
>Kindly check phone {{ $v.mobile.$params.maxLength.min }} number.</div>
For the above code in the textbox, I need to accept only numbers. and i need change the pattern of number to something like ""4356754356""(schould display numbers only in series)
Upvotes: 2
Views: 6640
Reputation: 103
for only number input add this on tag onkeypress='return event.charCode >= 48 && event.charCode <= 57'
it works for me
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
Upvotes: 2
Reputation: 7086
I need textbox [input] which accepts only numbers for the code. (phone number which accepts only numbers not characters).
So to accept only numeric characters, the acceptNumber()
method's rather complicated string manipulation needs to be modified.
A good way to know what's happening with a complex string manipulation is to break it down into sections.
This code:
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]:'');
Can be broken down into simple steps:
let thisValue = '(123) 456-7890';
let x = thisValue.replace(/\D/g,'');
console.log(`x: "${x}"`);
// x: "1234567890"
x = x.match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
console.log('x.match:', JSON.stringify(x));
// x.match: ["1234567890","123","456","7890"]
thisValue = !x[2]
? x[1]
:'(' + x[1] + ')' + x[2] +
(x[3] ? '-' + x[3] : '');
console.log(`thisValue: "${thisValue}"`);
// thisValue: "(123)456-7890"
Notice that the first item of the x
array is just the phone digits, which is what the OP is seeking:
this.value = x[0]; // "1234567890"
Here is a minimal version of the original code with the above change. Note that it filters out all non-numeric characters as they are typed.
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>
Upvotes: 0