Validating customer ID pattern in JavaScript

Posted on 2007-07-31
Medium Priority
Last Modified: 2012-08-14
I am trying to validate a customer ID in a field in a form using JavaScript. The customer IDs are in the following format:

xxx-xxx-xxx (numbers only)

I can validate the length but not the pattern., Is there a way to do this in JavaScript?
Question by:idnzor
LVL 14

Accepted Solution

bugs021997 earned 1000 total points
ID: 19601430
Here is a working example....

<script type="text/javascript">
var regex = /^\d{3}-\d{3}-\d{3}$/;

Phone Number: <input type="text" onBlur="if (this.value == '' || regex.test(this.value)) {} else { alert('Phone number must be: xxx-xxx-xxx'); this.focus(); }">
LVL 12

Expert Comment

ID: 19601657
You may consider a slightly more complex validation pattern that allows any format of phone number:
   (xxx) xxx-xxxx

Changing the regex to something like: /^\(?\d{3}\)?[\s-.]?\d{3}[\s-.]?d{4}$/ accomplishes this.  FYI the regex can be as complex or simple as you want.  If you have a specific set of patterns you want to accept but not others, tell us in words and we'll write the regex.

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question