Regular Expressions


Regular Expressions Exercises


Consider the following HTML code:

<!DOCTYPE html>
    <title>Regular Expressions</title>
    <meta charset="utf-8">
    <form action="myscript.php">
      Username: <input type="text" pattern="" name="username" required="required"/>
      <input type="submit" value="Try"/>


Taking advantage of regular expression restrictions defined in HTML 5, make sure the input only allows values that:


Add a new input field for the user’s real name. Make sure it only allows non-numeric characters that are not present in the following list:



Add a new input field for the zip code using the format NNNN-NNN or just NNNN.


Add a new input field for an IPv4 address that allows values like ( but not those with leading zeros ( Remember that each number should be smaller than 256.


Add a new input field for a MAC address. MAC addresses are composed by 6 words of 2 hexadecimal digits each separated by either an hyphen(-) or a colon(:). The separator should be the same for the whole field (i.e. this address should be invalid A0:B0-C0:D0:E0:F0. It should have been written like A0:B0:C0:D0:E0:F0 or A0-B0-C0-D0-E0-F0).


Add a new input field for a password (you can use a text type input to make it easier to debug). Make sure it only accepts passwords that:


Add some Javascript code that verifies if the username is included in the password. If it is, the submit button should not work and the password field should get a red border to signal that it is invalid.

Tip: Use the classList.add and classList.remove methods to add an error class to the password field and some CSS to draw the red border.

Alternatively you could use Javascript to change the pattern in the password field whenever the username changes to include a negative assertion with the username.


Using the same rules, use Javascript to validate each field on the fly. This means that fields should be validated as the user types the data instead of only validating them upon submission of the form:


Create a myscript.php file and verify the format for each input at the server. Print “ok” if every field has the correct values or “error in field $field” if any field has an invalid value.