简体   繁体   中英

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)

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(‐). 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

Try: <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. 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
  • 111222-3333
  • 111222333

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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