Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are three common ways for handling phone number input of a guaranteed format:</p> <p><strong>1. Accept all numerical input anyway</strong></p> <p>The likelihood of users with obscure numbers but still living in the US is higher than ever. Accepting all kinds of numerical input alleviates the concern as the number will only be useless if they gave you either not enough numbers or the wrong ones.</p> <p><strong>2. Split it into three text boxes of fixed lengths</strong></p> <p>A lot of financial software does this. Not sure why, specifically, but it seems to be rather frequent there. A recommendation is to advance the cursor after keypress to the next box if they've typed the max limit on the textboxes. Also, this guarantees you will get the numbers in whatever format you're expecting, because you can just append the resulting post variables together.</p> <p>Example of the HTML:</p> <pre><code>&lt;input id="phonePart1" maxlength="3" name="phonePart1"/&gt; &lt;input id="phonePart2" maxlength="3" name="phonePart2"/&gt; &lt;input id="phonePart3" maxlength="4" name="phonePart3"/&gt; </code></pre> <p>and a little jQuery snippet to merge the three in your format:</p> <pre><code>var phonePart1 = parseInt($("#phonePart1").val(), 10); var phonePart2 = parseInt($("#phonePart2").val(), 10); var phonePart3 = parseInt($("#phonePart3").val(), 10); var phone = "("; if (isNaN(phonePart1)||isNaN(phonePart2)||isNan(phonePart3)) { // Incorrect format } else { phone = phone + phonePart1 + ")" + phonePart2 + "-" + phonePart3; } </code></pre> <p><strong>3. Use a regular expression to match the number format</strong></p> <p>You can use a combination of regular expressions to match multiple numbers, or explicitly the one you are asking about. This is probably the technique you're looking for. This is the regular expression:</p> <pre><code>/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/ </code></pre> <p>You'd use it like this:</p> <pre><code>if (yourphonevariable.match(/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/)) { // it's valid } </code></pre> <p><strong>4. If you're looking to format the text itself with a mask...</strong></p> <p>Consider the jQuery plugin at <a href="http://digitalbush.com/projects/masked-input-plugin/" rel="noreferrer">http://digitalbush.com/projects/masked-input-plugin/</a>. User @John Gietzen suggested this to me outside of this post, so feel free to give him kudos for it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload