Chapter 4. Regex in Practice
In the previous two chapters, we covered Regex's syntax in depth, and at this point, have all the pieces required to build a real-world project, which will be the goal of this chapter.
Knowing Regex's syntax allows you to model text patterns, but sometimes coming up with a good reliable pattern can be more difficult, so taking a look at some actual use cases can really help you learn some common design patterns.
So, in this chapter, we will develop a form, and we will explore the following topics:
Regular expressions and form validation
By far, one of the most common uses for regular expressions on the frontend is for use with user submitted forms, so this is what we will be building. The form we will be building will have all the common fields, such as name, e-mail, website, and so on, but we will also experiment with some text processing besides all the validations.
In real-world applications, you usually are not going to implement the parsing and validation code manually. You can create a regular expression and rely on some JavaScript libraries, such as:
This demo will be for a site that allows users to create an online bio, and as such, consists of different types of 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.
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:
We get the name field in a similar way to how we got the form, then...
We are going to add one more input to our form, which will be for the user's description. In the description, we will parse for things, such as e-mails, and then create both a plain text and HTML version of the user's description.
The HTML for this form is pretty straightforward; we will be using a standard textbox and give it an appropriate field:
Next, let's start with the bare scaffold needed to begin processing the form data:
This code gets the text from the textbox on the page and then saves both a plain text version and an HTML version of it. At this stage,...
In this chapter, we covered a couple of examples that showed us how to both validate user inputs as well as manipulate them. We also took a look at some common design patterns and saw how it's sometimes better to simplify the problem instead of using brute force in one pattern for the purpose of creating validations.
In the next chapter, we will continue exploring some real-world problems by developing an application with Node.js, which can be used to read a file and extract its information, displaying it in a more user friendly manner.