The HTML5 movement has brought a substantial amount of new tools to the web developer’s arsenal. Today we will be discussing one of those tools known as the pattern attribute. The pattern attribute is specific to the form input tag. This new attribute allows us to test a field for a specific format before we submit the field’s data to the server.

Why would we need to do that?

Well in this scenario, we may be an e-commerce site that offers special discounts on our computers for students from local universities. In order to apply the discount to the product, we need to validate that this user is a student. To do so, we will be implementing the pattern attribute to check the form data’s pattern prior to executing the server-side code.

Note: In this tutorial we are using a pseudo function called form_validator.php. Ideally this function would first, check our database to see if the user has already applied the student discount to the product, and two, send a confirmation email to the user’s student e-mail account. This confirmation e-mail will confirm that the user has access to this e-mail account and isn’t just using one that they found on the internet. Since this tutorial is about the HTML5 pattern attribute, we will not be including the server side php function.

Base Code

We will start with a simple HTML5 form that accepts an email address and submits it to a form_validator.php function on the server.

You should have a basic form that looks something like this:


Validating Our Form Data

The above form’s markup certainly completes the task of sending an email address to the server, but it is accepting any e-mail address. We only want to accept an e-mail address at an .edu domain name.

We can use the pattern attribute and JavaScript regular expressions, to exclusively allow an email address from an .edu domain name.

Now if you try to submit the email address the form will notify you that the data in the email input is not compliant with our specified format.


However, if you attempt to submit the email address the form will accept this format and submit the e-mail input’s data to the server.

Of course if you want to limit the schools that your discount applies to, you can do so by adding them into the regular expression like so:

The above code will only accept an email address from a Stanford or Cal Berkeley student.


And that’s the basics of the pattern attribute. It is a pretty simple tool that allows you to only accept a specified format without the use of JavaScript.

Download Source Files