Introduction to Form Validation
Data submitted through forms are stored as strings. Strings are a fundamental data type in computer science representing a series of characters “strung” together. As humans, we can intuitively recognize patterns within strings, and this allows us to catch errors. Try to notice what’s wrong in the following examples:
- My zip code is 9021
- The ct meowed
<h1> Hello, World! </h2>
In the first example, we had the letters of the alphabet presented in order but interrupted by an out of place
In the second, we left off the 5th digit of a famous zip code. In the
third, we omitted the “a” from the word cat. In the final example, we
wrote some HTML with an
<h1> opening tag but an unmatching
closing tag. If you picked up on these mistakes, it’s because your
brain has been trained to expect patterns in certain types of data.
Unlike humans, who can get this training passively over time, computers have to be precisely programmed to recognize patterns. To specify patterns for the computer to recognize, we use a special language called _regular expressions_—also known as regex or regexp. A regular expression is a sequence of characters representing a pattern. We can use that pattern to match a string, match parts of a string, confirm that data is formatted acceptably, or even replace parts of strings with different characters.