Code Help
Hey Guys, I need your help in following Javascript code. I want my input field to format values in this format. +92 ###-####-###
function phoneFormat(input) {
input = input.replace(/\D/g,'')
var size = input.length;
if (size > 0) {
input = "+91 " + input;
}
if (size > 4) {
input = input.slice(0, 6) + "-" + input.slice(6);
}
if (size > 9) {
input = input.slice(0, 10) + "-" + input.slice(10);
}
console.log(input.length + " and size is " + size);
return input;
}
But it is not working as expected.
Anyone Who can help me with that12 Replies
if your input are 10 digits (ignoring the spaces or other chars), then you could just do
But, there will be a lot of edge cases. What if someone already puts in the country code, or if there are not 10 digits, or whatever (don't expect a user to allways have it right)
there are some libraries that can help you with it
Thanks for this code but i am writing code in VanillaJs so can not use library + What is the issue with my code.
didnt run your code my self to check, but you are overriding the input with each if-statemenet. after the first if, the input has already +91 added. then in the next step you have to account for that
Okay, Thanks buddy
your output is
"+91 12-345-67890"
so there is a miscalculation with the slice index. Think you didn't account for the space after +91for size 3 also slice is not working, and one more issue after writing all the 10 numbers, value changes to +91-91-919-9191
but i'm not sure why you would need the if statements
for condition checking on every user input Here is html :
<input type="phone" id="mobileNumber" class="editable-input rounded-3 form-control form-control-lg border hover:border-primary border-2" onInput="this.value = phoneFormat(this.value)" value="">
ah okay i see, you want to check/format it live
yup
any solution till now
ohw sorry, i was totally forgotten about it.
I think this should do the trick
https://codepen.io/MarkBoots/pen/xxMBKJW?editors=1111
but you also still have to account for other keystrokes, such as the delete and backspace