简体   繁体   English

如何在输入框中仅输入有效的电话号码?

[英]How can i input only valid telephone number in input box?

I am trying to input a telephone number in an input box like this (ex. 111-222-3333) 我正在尝试在这样的输入框中输入电话号码(例如111-222-3333)

so I use this code: 所以我使用这段代码:

<script type="text/javascript">
    function validate(evt) {
      var theEvent = evt || window.event;
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode( key );
      var regex = /[0-9]|\-/;
      if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
     }
    }
</script>

I can now only input telephone number using integer(0-9) and '-' but the problem is user can also type another hyphen(‐) after a hyphen(‐). 我现在只能使用整数(0-9)和'-'输入电话号码,但问题是用户还可以在连字符(-)之后键入另一个连字符(-)。 Or user can type numbers not in a telephone format 或者用户可以输入非电话格式的号码

Please help me, i really need this one..thanks:) 请帮助我,我真的需要这个..谢谢:)

Have a look at this: http://dev.w3.org/html5/markup/input.tel.html 看看这个: http : //dev.w3.org/html5/markup/input.tel.html

Try: <input type="tel"> 试试: <input type="tel">

How far are you willing to go to validate the phone number? 您愿意多久验证一次电话号码? You can make it more or less hard for the user to input an incorrect number, but in the end you will never be able to fully validate the number unless you manually pick up the phone and confirm each user or confirm via some text message service if it's mobile only. 您可以使用户或多或少难于输入一个不正确的号码,但是最终您将无法完全验证该号码,除非您手动拿起电话并确认每个用户或通过某些短信服务进行确认(如果有)。它只是移动的。

If you are trying to "help" the user so he/she knows what pattern the server expects, you can f.ex use three input fields next to each other with a dash in between. 如果您试图“帮助”用户,以便他/她知道服务器期望的模式,则可以f.ex使用彼此相邻的三个输入字段,中间使用一个短划线。 It's probably much more useful than adding some advanced event logic that validates the pattern as the user types. 它可能比添加一些高级事件逻辑有用,该逻辑可以在用户键入时验证模式。

Try this 尝试这个

/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/

will support 将支持

  • (111)-222-3333 (111)-222-3333
  • 111-222-3333 111-222-3333
  • 111222-3333 111222-3333
  • 111222333 111222333

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM