scriptygoddess

03 May, 2008

Phone number validation with jquery

Posted by: Jennifer In: Javascript|jquery

One of the things I've been playing around with a lot recently is jquery. Why I didn't jump on this bandwagon sooner, I'm not sure, but I am kicking myself for it. So I am still a bit of nub on the jquery front – but I like to think I pick things up quickly. 😀

So one thing I am now using jquery regularly for is form validation. Previously, form validation used to mean a lot of script writing, not to mention a fair amount of dread.

Now it's quite painless.

My current usage of that plugin is pretty basic until I get a better handle of it. But one thing that I have been requested a number of times, is to add validation for a phone number – which is not included in that plugin. I'm not sure this is the "right" or best way to do it – but it does work. :)

The functions are basically the same as those provided here with some minor modifications and altered to be used with the jquery plugin.

First of course you include the jquery javascript file:
<script language="javascript" type="text/javascript" src="/js/jquery.min.js"></script>

Then the validation plugin:
<script type="text/javascript" src="/js/jquery.validate.pack.js"></script>

Then you add the function to check the phone number:
<script type="text/javascript">
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 10;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "Please enter a valid phone number");

Some "helper" functions:
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}

Then the line that makes the jquery run:
$(document).ready(function() {
$("#myform").validate();
});
</script>

To use the jquery validation plugin – I was just adding "required" as a class to those fields that were required. Like this:
<input type="text" name="FirstName" class="required" />

You can check email structure by also adding the class "email".
<input type="text" name="EmailAddress" class="required email" />

And now, using the code above, if you add the class "phone" – it will check a phone number.
<input type="text" name="PhoneNumber" class="required phone" />

(My code above allows for some additional characters beyond just numbers – so that it will accept parens around the area code – dashes or periods between the numbers and "e" "x" "t" characters as well – in case someone needs to include an extension.)

Typical disclaimer – like I said – I'm still a nub at jquery. There may be a better/easier way to do the above, so as always feel free to chime in if you know what that better/easier way is…

Updated 5/5/08 I do see a "phone" method in the "additional-methods.js" file… but I needed it do things a little differently… (like allowing extension numbers etc.)

Updated 5/29/08 Had some issues with the method not allowing phone fields to be optional and only checking the values if something was entered (when optional). Fixed that now.

Updated 7/1/08 As JT noted in the comments with regex this can be simplified. JT provided the following code:
function isValidPhoneNumber(ph) {
if (ph == null) {
return false;
}
var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
// 10 is the minimum number of numbers required
return ((/\d{10,}/i).test(stripped));
}

So to update the jquery:
$.validator.addMethod("phone", function(ph, element) {
if (ph == null) {
return false;
}
var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
// 10 is the minimum number of numbers required
return ((/\d{10,}/i).test(stripped));
}, "Please enter a valid phone number");

And then you can loose the other "helper" functions. (Thanks JT!!)

12 Responses to "Phone number validation with jquery"

1 | links for 2008-05-05 | iKeif

May 5th, 2008 at 10:36 am

Avatar

[…] I've used before – and it's handy to have it cross library!cache javascript jquery js loader scriptygoddess » Blog Archive » Phone number validation with jquery 14 hours agojQuery phone number validation. Adding it to the pile.javascript jquery js validation […]

2 | spin

May 23rd, 2008 at 6:28 am

Avatar

thanks for this. Saved me lots of time and hassle

3 | Bob S

June 20th, 2008 at 12:45 am

Avatar

I'm pretty new to jQuery, too, but let me make one recommendation for your future sites:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> (I don't know what your site will do w/ HTML in comments, so please bear with me). Google is now hosting jQuery along with various other popular JavaScript frameworks at addresses such as the above. The best description of this is at http://ajaxian.com/archives/announcing-ajax-libraries-api-speed-up-your-ajax-apps-with-googles-infrastructure . For me, a very low-level developer, this means three things: 1) I never have to download jQuery again — unless I'm doing off-line development, which is pretty much never; 2) no load on my server for serving up the jQuery library; 3) with enough people using this, the odds are good that the user will already have downloaded the self-same file at the behest of another site using the same Google hosting, and will save a little time and bandwidth.

4 | JT

July 3rd, 2008 at 6:21 pm

Avatar

I'd suggest you could make this code a lot simpler by converting it to a regex – replace '[()+ ]*|ext\.' with nothing, then match to '[0-9]{1,}'. This will remove the allowed characters then assert the numeric only and length conditions in 2 lines.

This should be more performant, maintainable and readable than the current solution. Note I haven't tested the above regexes, but they'd be close to the mark.

5 | Jennifer

July 3rd, 2008 at 8:32 pm

Avatar

JT – if you can write the exact regex I can update the post. Unfortunately, regex is not something I've ever been able to wrap my head around. I wish I knew it better – but it just completely stumps me.

6 | JT

July 3rd, 2008 at 9:59 pm

Avatar

function isValidPhoneNumber(ph) {
if (ph == null) {
return false;
}

var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");

// 10 is the minimum number of numbers required
return ((/\d{10,}/i).test(stripped));
}

Literal regexes are surrounded by slash (/) characters, like quotes surround string literals. The syntax is /[regex]/[flags].

So, the first regex is [\s()+-]|ext\.? which means: match either a whitespace, parenthesis, +, – OR the literal ext, optionally ending in a full-stop (period). When used with the replace function it removes the allowed characters from the string, leaving you with only numbers (if it's valid).

The next regex is \d{10,} which means match a string that consists of at least 10 digits, more is allowed. If there are less digits, it won't match. If alpha chars are present, it won't match. The number 10 is your minimum number of digits.

Note that in your solution the number 200txxxex200xxx200xxt.x2 is valid.

http://www.regular-expressions.info/ is a great regex resource, and the Mozilla JavaScript reference can be helpful too (http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference).

I hope this helps!

7 | Anand

July 31st, 2008 at 1:59 pm

Avatar

Hey Scripty Goddess,

Can you write up a similar function to validate the US Zip codes by State?

If I have a drop-down containing all the states and then a text box for entering Zip, then my zip code should be validated according to the State selected above.

I tried using an Ajax callback to a Page Method and then checking the zip codes with State in the database, but its turning out to be too complicated.

Anand

8 | Rob

August 12th, 2008 at 7:08 am

Avatar

Thanks! Worked like a charm!

9 | Andrew Woods

September 1st, 2008 at 10:17 am

Avatar

I needed to check for valid US phone numbers, so I wrote this function. HTH

function validatePhoneNumber(phoneElement){

if (isEmpty(phoneElement)){
return false;
}

var regex = /^((\+?1-)?\d\d\d-)?\d\d\d-\d\d\d\d$/;
console.log("phone=" + phoneElement.value);

if (phoneElement.value.match(regex)){
return true;
}
return false;
}

10 | brindle

September 16th, 2008 at 12:00 am

Avatar

Hey Scripty,

Here is a regular expression for matching phone numbers – 10 digit phone numbers. An explanation can be found here http://www.websina.com/bugzero/kb/regexp.html at bottom of the page.

re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/;

This is a little more robust than previous expression in that parentheses and separators are optional and can be "-", "/" or "."

11 | jQuery 3 ?? at ?????????????

January 14th, 2009 at 11:51 pm

Avatar

[…] jQuery????????Jennifer Stuart ???????? JavaScript ????????????????????????????? jQuery ??????? […]

12 | ArticleSave :: Uncategorized :: Happy 3rd Birthday, jQuery

January 16th, 2009 at 12:07 am

Avatar

[…] a developer and you haven't tried out jQuery yet – you probably should. As Jennifer Stuart wrote when she finally did this Spring, "Why I didn't jump on this bandwagon sooner, […]

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements