O'Reilly logo

JavaScript Regular Expressions by Gabriel Manricks, Loiane Groner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validating fields

In this section, we will explore how to validate different types of fields manually, such as name, e-mail, website URL, and so on.

Matching a complete name

To get our feet wet, let's begin with a simple name field. It's something we have gone through briefly in the past, so it should give you an idea of how our system will work. The following code goes inside the script tags, but only after everything we have written so far:

function process_name() { var field = document.getElementById("name_field"); var name = field.value; var name_pattern = /^(\S+) (\S*) ?\b(\S+)$/; if (name_pattern.test(name) === false) { alert("Name field is invalid"); return false; } var res = name_pattern.exec(name); data.first_name = res[1]; data.last_name ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required