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 ...
Get JavaScript Regular Expressions 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.