Search This Blog

Saturday, January 15, 2011

Validate number input with Regular Expression in JavaScript

Validating inputs submitted by users is always a big challenge for writing any application that requires users input. For example, if we have a mortgage calculator app, we must validate and make sure that users don't enter a letter for the interest rate box.

For the mortgage calculator, it is easy to validate input that we don't need regular expression. But a lot of problems require complex validation if we don't know regular expression. For example, validate the zip code input which must be five digit long such as 22003 and 97850.

In this post, we'll learn how to do such validation with JavaScript. However, the regular expression pattern can be applied for other languages as well.

Let's take a look at this JavaScript code:

function validateZipCode(zipCode)
{
  var pattern = /^\d{5}$/;
  return zipCode.search(pattern);
}

This code will return 0 if the input contains only a string of five digits. Otherwise, it will return -1. Pretty neat right? Let's break down the pattern.

  • / marks the start of the pattern
  • ^ specifies that the pattern must start at the beginning of the input string
  • \d{5} means pattern of five consecutive digits in the string. For example, 9780 is a match but 98t034 is not. We can change the number inside { } to match more digits. For example, \d{6} matches six consecutive digits.
  • $ specifies that the end of the pattern must also be the end of the input string. ^ and $ combines to make sure that the input contains only five digits and nothing else. For example, t97850 matches the \d{5} and \d{5}$ pattern but doesn't match ^\d{5}$ and 97850f matches \d{5} and ^\d{5} but doesn't match ^\d{5}$. Only 97850 matches ^\d{5}$ pattern.
  • / marks the end of the pattern. Notice that a pattern must be enclosed within a pair of / / signs.

No comments:

Post a Comment