Lab 8: Regex and Form Validation with HTML5/JS/PHP

Agenda

In this lab, you will learn more about regex and validation methods, with a number of exercises. Due to student interest, we have provided more material than you should expect to finish, but you can prioritize what you are interested in exploring most.

We encourage you to finish the rest on your own, and refer to some readings/examples posted from lecture yesterday for more resources!

Exercise 1: Regex Hybrids!

In this exercise, you will use regex with PHP to display photos of... animals. You can find the starter files and images in this hybrids.zip folder.

You can find a runnable version to reference the expected behavior here.

Slides with more details are provided below.

Exercise 1: Overview (1/2)

The hybrids.html page uses hybrids.js (completed for you) to make GET requests to regexhybrids.php and display images on the page using the plain text results. When #submit-one button is clicked, a request will be made to regexhybrids.php with a query parameter of animal and a value of whatever the user input into the #animal text input box.

If the user clicks on #submit-all instead, a request will be made passing animal=all as the query parameter. The response will then be used to populate the #results area with the resulting images.

Exercise 1: Directions (2/2)

Modify regexhybrids.php to use regular expressions so that it will return a plain text result of all images matching the GET parameter (each on their own line) if given any animal query parameter (other than "all"). If passed animal=all, it should instead return a plain text result of all images in the images/ folder. Recall you can use preg_match to match image names against a given regular expression.

Exercise 1: Solution

Example solution: PHP Source

Exercies 2: More Regex Practice

Beyond just matching hybrid animal image names, regex is a very powerful tool, especially when validating text or implementing find/replace features. But it takes practice! Below you will find a collection of exercises to get you more practice.

Refer to yesterday's lecture slides for some more examples of different regex features, and remember that there are often several ways to write a correct regular expression!

Regex Practice Exercises (1/2)

Write regex that would match each of the following patterns:

  • UW Student ID numbers (non-negative 7-digit numbers) (try it)
  • DNA sequences (non-empty strings containing only A, C, G, T, ignoring letter-casing) (try it)
  • camelCased strings containing only letters and at least one capitalized letter (try it)
  • A 16-digit credit card number, with optional dashes for every four digits (e.g. 1234123412341234, 1234-1234-1234-1234 and 1234-12341234 should match, but not 12341234123412341234 or 1233 or 1234-1234-1234-1234-) (try it)
  • A version of "Google" with an odd number of o's (try it)
  • A real number such as 3.14 or -42.8775 (try it)
  • Dollar amounts of at least $100.00 (try it)

Regular Expressions Exercises (2/2)

  • Strings that contain at least two consecutive vowels (A, E, I, O, or U), ignoring letter-casing (try it)
  • A https URL ending with "edu", "com", "org", or "gov" with website names in all-lowercase, possibly containing digits, with at least one "." in the path (e.g. "https://www.cs.washington.edu") (try it - only worry about passing/failing the specified tests, there are more complicated types of urls you could also match)
  • Digimon names: strings starting with a capital letter and ending in "mon" (only letters otherwise) (e.g. "Agumon", "Gabumon", "Patamon" but not "mon, Mon", or "Agu") (try it)
  • Binary strings with at least one 1 and at most two 0's (try it)
  • A capitalized first name, single (upper-case) middle initial, and capitalized last name with a single space between each and with the first and last name both having lengths less than 10 letters (try it)

Regular Expressions Exercise Solutions (1/2)

  • UW Student ID numbers (non-negative 7-digit numbers) (one solution)
  • DNA sequences (non-empty strings containing only A, C, G, T, ignoring letter-casing) (one solution)
  • camelCased strings containing only letters and at least one capitalized letter (one solution)
  • A 16-digit credit card number, with optional dashes for every four digits (e.g. 1234123412341234, 1234-1234-1234-1234 and 1234-12341234 should match, but not 12341234123412341234 or 1233 or 1234-1234-1234-1234-) (one solution)
  • A version of "Google" with an odd number of o's (one solution)
  • A real number such as 3.14 or -42.8775 (one solution)
  • Dollar amounts of at least $100.00 (one solution)

Regular Expressions Exercise Solutions (2/2)

  • Strings that contain at least two consecutive vowels (A, E, I, O, or U), ignoring letter-casing (one solution)
  • A https URL ending with "edu", "com", "org", or "gov" with website names in all-lowercase, possibly containing digits, with at least one "." in the path (e.g. "https://www.cs.washington.edu") (one solution)
  • Digimon names: strings starting with a capital letter and ending in "mon" (only letters otherwise) (e.g. "Agumon", "Gabumon", "Patamon" but not "mon, Mon", or "Agu") (one solution)
  • Binary strings with at least one 1 and at most two 0's (one solution)
  • A capitalized first name, single (upper-case) middle initial, and capitalized last name with a single space between each and with the first and last name both having lengths less than 10 letters (one solution)

Exercise 3: E-Pizzeria!

In this exercise, you will learn more about ways to use input validation in HTML, JS, and PHP to validate an online pizzeria order, while exploring different methods for providing a user-friendly experience. You may download the starter files in this epizzeria.zip folder.

E-Pizzeria exercise screenshot

There are three different parts to this exercise, each which serve to demonstrate different validation methods (they do not depend on one another). To keep things organized, we have provided you nearly-identical starter code in the three "part-*" folders located in epizzeria.zip. Feel free to focus on the ones you'd like to practice most.

Exercise 3: Warm-Up

Before we start implementing validation of our page, what do you think should be true about the user's selections before considering the order successful (make sure to take a look at the epizzeria.html output)? After you have brainstormed some, continue down for more instructions.

Exercise 3: Validation Criteria

Here are some validation criteria which you will now implement for the E-Pizzeria form. If you thought of others, you may also add them for additional practice. These criteria will be used for validation using HTML5, JavaScript, and then PHP in the subsequent sub-exercises below.

  • Tips must be a non-negative real number with two digits after the decimal
  • State must be a two-character string of uppercase letters
  • Address must begin with an integer followed by any number of words, such as "1234 Fifth St." (allow "." at the end of any word) (example rubular tests)
  • Customers may not order more than 2 types of cheese (only for Part II and Part III)
  • Customers may not order more than 3 types of toppings (only for Part II and Part III)
  • There must be a value selected for each of "Crust Options", "Sauce", and "Size" - for Part I you may set any radio button of your choice for these options to be checked by default
  • All input boxes in the "Payment" section must be non-empty

Exercise 3 Part I: HTML Validation

Use HTML form validation to ensure the criteria is met, using the starter code in the part-i-html-validation folder of your unzipped epizzeria folder. HTML5 includes various features to validate user input without client-side verification (JavaScript) or server-side verification (PHP).

Note: In order to use HTML5 validation features, you'll need to include your <input> tags in a a <form> element - we haven't covered forms much in this class, but they are another way to group form inputs, and happen to be needed for HTML5 form validation. You can find more information here! and a documented example posted from lecture here: (zip).

HTML5 Validation Tips

Use the pattern attribute to require certain regex patterns in the HTML order form. You should also use the required attribute to require an input item to be filled before submitting. To give customers example expected formats of text/number inputs, either add text to the side of the corresponding input box or use the placeholder input attribute.

Exercise 3 Part II: JS Validation (1/2)

Next, we will get some practice using client-side validation to ensure the criteria is met. Edit part-ii-js-validation/epizzeria.js in the unzipped epizzeria folder to validate the user's order with the same criteria from Part I, but without HTML5 pattern attributes (there is a fresh template for you to use in your part-ii-js-validation/epizzeria.html).

On the slide below, you can find information about using regular expressions in JavaScript.

Regular Expressions in JavaScript

Create regular expressions like this: let pattern = /cse154/i or with the RegExp constructor: let pattern = new RegExp(/cse154/, 'i')

Some JavaScript string methods can take Regular Expressions, like search and replace (example search/replace code demo)

let pattern = new RegExp("Spring", "i"); 
// or let pattern = /Spring/i;
let str = "CSE154: Web Programming Spring 2018";
let newStr = str.replace(pattern, "Autumn");

JS

Note there are a variety of useful methods you may find for different things, but there are also a few nuances depending on whether you are using the RegExp or String type in JavaScript. Refer to this helpful page for more of an overview!

Exercise 3 Part II: JS Validation (2/2)

Your JS code should display helpful error messages of your choice in the ul#order-results at the top of the page when the #submit button is clicked and the input does not pass the criteria (also remove the .hidden class from #order-results-header to introduce the error list if there are any input errors; remember to hide the header when the user has fixed the input errors and tries re-submitting!)

Exercise 3 Part III: PHP Validation (1/2)

Now use server-side PHP validation to ensure the criteria is met using the provided starter code in the part-iii-php-validation folder). The provided starter JS makes a POST request to a starter epizzeria.php service when the #submit button is clicked.

As shown briefly in lecture yesterday and given in the starter JS, you can conveniently pass a form DOM element as a parameter to the FormData constructor in a POST fetch request as follows:

let form = document.querySelector("form");
let params = new FormData(form);
fetch(url, { method : "POST", body : params)
  .then(checkStatus)
  ...
});

JS

We have also provided most of the JS code for you in but you may need to edit some of it after finishing epizzeria.php.

Exercise 3 Part III: PHP Validation (2/2)

Your PHP script should then process the POST parameter array and verify their validity based on the same criteria as Part I and Part II, but send a JSON response back to the client whether or not their order was "successful". It is up to you to choose how you want to return this JSON, but here's a simple example:

{ "status" : "successful", 
  "message" : "You successfully ordered your pizza for $10.25!" }

JSON

Note that since this is just a practice exercise, we aren't worrying about storing orders as external data, just verifying that the POST parameters are valid using PHP. Output any invalid requests as a descriptive error message (you may want to consider adding a "details" key in a JSON response with an array of specific messages for each invalid POST parameter sent; this would make it easier to add an <li> element for each error in the ul#order-results).