0

I found this code on some website and I don't know how to validate phone number in real time with javascript.The number should appear as such:(123)-456-7890 and the hyphens,brackets and spaces should be handled by the script and not after all the 10 digits are typed in.

I'm using this regular expression but I don't know how to validate it in real time: /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/

How can I do this phone validation in real time with javascript so that no user will be allowed to add brackets/spaces/hyphens,that should be handled by script?

  • Does this answer your question? [Implement an input with a mask](https://stackoverflow.com/questions/12578507/implement-an-input-with-a-mask) – ggorlen Aug 16 '20 at 06:40
  • what about show what you do ? – Baruch Mashasha Aug 16 '20 at 06:40
  • Particularly [this solution from trincot](https://stackoverflow.com/a/55010378/6243352). – ggorlen Aug 16 '20 at 06:41
  • With "in real time" do you mean as the user type in data? It's tricky to do, and you hit all kind of ux issues if you are not smart about it. For instance is 1234 a valid phone number? They didn't type in the (, ), and -? Is might be a valid prefix but it's not a valid number. Also, you don't want to interrupt a user that is typing stuff. The format you use here, btw, is non-standard opposed to (123) 456-7890. What about extensions? Use html5 type=tel. Consider constrained input (say, only accept numbers and maybe a-z), auto-format, and then only validate when user is done with field. – Allan Wind Aug 16 '20 at 09:02

0 Answers0