Validating User Data

We'll look at validating three specific kinds of input: phone numbers, email addresses, and credit card numbers. Our first example will contain the first two, and at the end of the chapter we'll look at validating credit cards.

Our phone numbers must have an area code—that's all we really care about. We don't care if someone enters “415-555-1212” or “(415) 555-1212” or “415.555.1212”—we just need 10 integers. We'll check both the phone number and the fax number. Of course, we only need to check if the format is right if the user entered something in those fields.

For the email, we need the presence of an “@” and a “.” and we want to make sure the last “.” comes after the @ sign.

Our HTML stays exactly the same. We'll create ...

Get Advanced JavaScript™: Insights and Innovative Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.