最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery masked input have only first number optional rest mandatory - Stack Overflow

programmeradmin3浏览0评论

Im using jquery masked input plugin and need to have a phone field with the following format:

1 (222) - 000 - 1114

my code looks like this:

$("#myPhone").mask("9 (999) - 999 - 9999");

now i cant seem to get it to work to make the first digit optional but the rest mandatory. So the following numbers are valid:

1 (222) - 000 - 1114
  (222) - 000 - 1114

and the following numbers are invalid

1 (222) - 000 - 11
  (222) - 00  - 0011

using "?9 (999) - 999- 9999" will not work since it makes the whole thing optional

If this cant be done in masked can someone help me out with regular expression to achieve this?

Im using jquery masked input plugin and need to have a phone field with the following format:

1 (222) - 000 - 1114

my code looks like this:

$("#myPhone").mask("9 (999) - 999 - 9999");

now i cant seem to get it to work to make the first digit optional but the rest mandatory. So the following numbers are valid:

1 (222) - 000 - 1114
  (222) - 000 - 1114

and the following numbers are invalid

1 (222) - 000 - 11
  (222) - 00  - 0011

using "?9 (999) - 999- 9999" will not work since it makes the whole thing optional

If this cant be done in masked can someone help me out with regular expression to achieve this?

Share Improve this question edited Mar 12, 2013 at 20:09 GGio asked Mar 12, 2013 at 20:03 GGioGGio 7,65311 gold badges46 silver badges85 bronze badges 2
  • I would first check if there are 11 digits, and after that use a mask in a function. – Iwo Kucharski Commented Mar 12, 2013 at 20:09
  • @GGio Yeah how do you make sure the first digit is exactly a digit? In my case I want know if it is a + – Mukus Commented Feb 25, 2020 at 4:40
Add a comment  | 

2 Answers 2

Reset to default 18

Try this:

$.mask.definitions['~'] = '([0-9] )?';
$("#myPhone").mask("~(999) - 999 - 9999");

It is not perfect, but you can use number or whitespace:

$.mask.definitions['~'] = '[0-9 ]';
$("#myPhone").mask("~(999) - 999 - 9999");
发布评论

评论列表(0)

  1. 暂无评论