Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

HTML5 and CSS3 Part 6: Formidable Forms with HTML5

5.00/5 (1 vote)
20 Apr 2014CPOL13 min read 9.9K  
Let's blow the doors off the boring form. Learn the basics and then get into the advanced, yet easy, inputs and form actions.

Introduction

Ever wanted to gather information from your visitors but weren't sure how? Maybe you have an idea of how to but you aren't really sure if it is safe. If you fall into one of these categories or if you just want to review the new features of HTML5 forms, this article is for you. We will start with the basics of web forms. From there, we will dive into the different pieces that make up a form. Finally, we will put everything we have learned together into a example form that takes advantage of the different elements that we have worked through. As always, we are going to stay focused on our destination. We will not be taking detours along the way that would confuse the issue or make it broader than necessary. Let's jump right in.

Basic Forms

Capturing information on a web page is done primarily using the form tag. Instead of just putting input fields, checkboxes, buttons and other items on the page randomly, we use the form tag to group these elements together. This serves a couple purposes. First, it groups the form elements together. This is a visibility issue (the items appear on the page in a grouping that indicates relation) but it is also tells the machines that read your site that these elements go together. Remember that it isn't only the person that sees your web page that views your site. Second, grouping elements inside a form allows you to indicate which data inputs you want to send to the server when you submit the form. For instance, you could have two or more forms on one page. If you weren't using a form tag, how would you indicate which inputs to send the data from? Finally, when your user is on an input in your form and they hit the return key, your page can automatically submit the data as if they hit the submit button. So, besides it being the "right thing to do", there are a number of reasons why we use the form tag.

OK, so far we know that we need a form tag but what is a form really? A form consists of a few major parts. First, there is the outer form tag. This groups all of the inputs together. It also has a few key attributes that store important information about the form. Inside of the form tag, we put one or more input elements. These can be textboxes, checkboxes, radio buttons, dropdown lists, etc. This is where you capture the information from the end user. Finally, we include one or more buttons to perform actions on our form.

Personally, I am a visual person. I like to see something, especially in use, in order to better understand it. To that end, let's look at a typical form and then we can dissect it:

HTML
<form name="userform" action="formprocessor.php" method="post">
    <p>
        First Name: <input name="firstName" type="text" />
    </p>
    <p>
        Last Name: <input name="lastName" type="text" />
    </p>
    <p>
        Over 18: <input name="over18" type="checkbox" />
    </p>
    <p>
        <button name="process" type="submit">Process</button>
        <button name="clear" type="reset">Clear</button>
    </p>
</form>

That gives us a form that looks like this:

Image 1

Pretty basic but there is a lot to unpack here. Let's move right into the elements of a form.

Form Elements

The Form Tag

On the form tag itself, we see that it has a few attributes. First is the name. This identifies the form on the page and when it is uploaded. Next is the action attribute. This is where the data will be sent when the form is submitted. Typically this is a server-side page that accepts the data and then stores it. This article is about the form itself, so we won't be worry about the server-side processing of form data. Note though that this page can be of just about any type. It could be a plain html form, an ASP page, a PHP page (like this example is using) or something else. The final attribute to notice is the method. In this case, it is specifying POST. HTML has a number of ways to send data. These different methods each have their purpose and use. In this case, we will typically use either the GET or POST method. In simple terms, the GET method (which is default if you do not specify a method) will submit the data to the server page via the URL. In our case, that would look like the following:

/formprocessor.php?firstName=Tim&lastName=Corey&over18=on&process=

Note the question mark (?) after the php page This specifies that the following items are attributes. Then we have each field (by name) and what its value is. The last item, process, is blank. That is the submit button. We will get to this in a minute. So, that is how GET works. That might work for a simple form such as a search box, where the data is not sensitive. However, if you are capturing any user-sensitive data this isn't a good idea. That is where the POST method comes in.

POST does not put data in the URL. Instead, it sends the data as part of the packet of information sent to the server. It is not visible to the user. This is a much safer method and it should, in my opinion, be the default method for sending data. Note that this does not mean your data cannot be captured. It just means that the first step to securing your data has been taken: the data is not visible on the page or in the URL. The next step would be to use SSL to protect the transmission of the data to the server. Again, that is outside the scope of this article so we will not be covering the installation of SSL. Just know that forms containing sensitive data should be on a page that utilizes SSL.

One final differentiator between GET and POST is the size of the data. URLs are limited to 2,000 characters. That seems like a lot until you ask for user feedback. A fired-up user will easily surpass 2,000 characters in a feedback form. If you try to use the GET method to send your form data, your user will get an ugly error message and you won't get that data. POST, on the other hand, is not affected by this limitation. This means you can capture your users opinions, their images, files and other large items without difficulty.

Bottom line, you use GET if you don't mind if your data is displayed in the URL and if it is short enough. This is beneficial for items like searches, since the user can save the URL and come back to the page later (since the search data is stored in the URL). It is not good for sensitive data or for large amounts of data. POST is great for sensitive data, large amounts of data and for most any use. It is not good, however, for allowing your user to recreate a page later using a saved URL.

Input Tags

Input tags are where the data gets captured. In this case, I specified two different types. First is the text type. This is your standard text box, used for capturing one line of information (such as a search box, name capture, etc.) Next is the checkbox. This is the boolean capture (yes or no). Note that the difference is only in the "type" attribute. This is how most of the input fields are differentiated. We will get into the different types in the next major section. The other attribute that all of my inputs have is the name attribute. This is what is used to identify which field the data is associated with. If you look at the GET url I posted above, you will see firstName, lastName, over18, and process. Look familiar? Each is the name of an input (a button is considered an input). Obviously, this is extremely helpful in identifying what the data is that is being sent to the server.

Buttons

Technically, a button is an input type. In fact, you can use the input element to specify the "submit" and "reset" types like so:

HTML
<input name="process" type="submit" value="Process" />
<input name="clear" type="reset" value="Clear" />

These two input elements could replace the buttons and they would work exactly the same.

Either way you do it, the submit and reset types are special input types. The submit type will package up the data on the form and send it to the URL specified in the form's action attribute via the method specified (GET or POST). The reset type clears the form's data and resets it back to what it was when you first loaded the page. The submit button is required but the reset button is not. Also note that while submit and reset are pretty good words to indicate what each button does, you can modify what is displayed. This is done by setting the value property (or putting data between the button open and close tags). In my case, I set the value to Process instead of Submit. One common way that the submit button is modified is to set the value to "Search" on search forms. That makes it a bit clearer than "Submit".

Form Input Types

Now that we have gone over the basic parts of a form, let's look at each input type in more detail. There are a lot, so I will give you the type and then give you a basic explanation of what each does. For most of these, the input field looks like a standard textbox but it has extra features. Sometimes the difference may only be semantics. It may only be to tell the machine reading the page that it is a specific type.

  • color - Used to pick a specific color. Shown as a color picker typically.
  • date - Used to pick a date (no time). Usually a date picker is attached to this input field. You can either type in the date or pick one from the list.
  • datetime - Used to specify a specific date and time in GMT (Greenwich Mean Time). Can be displayed as a picker but typically just shown as a textbox.
  • datetime-local - Same as datetime, only the value is assumed to be in the local time zone.
  • email - Used to store an email address (or a list of them separated by commas if it is enabled). It enforces a proper email address.
  • month - Used for storing the month and optionally the year as well. This can be displayed as a textbox or as a dropdown that has January through December listed.
  • number - Can only store a valid number.
  • password - This is an older input, but it is important to mention. It does not display the value in the box but it stores the information in the back end. The user just sees a star each time a key is pressed.
  • range - Stores a number. It displays a slider that is used to select the number.
  • search - Used for styling and semantics only. Works just like a textbox.
  • tel - Used to store phone numbers, but does not enforce a specif layout scheme.
  • time - Used to store a time. This does not give an indication of the time zone.
  • url - Used to store valid URI strings. It requires the user to specify a valid URL (must start with http://, https://, ftp://, etc.)
  • week - Used to store a week number and optionally a year as well.

For all of these new input types, the implementations vary by browser. The cool thing is that if a browser does not yet have a custom control to handle a specific type, it will revert back to a basic input box (which can capture the data for any of these new types). It may not be as convenient to type in a color value, for example, but it is better than nothing.

Form Attributes

To make forms even better, there are a number of attributes you can utilize to improve the functionality of your form. Let's look at a few of them:

  • value - This is the starting value for an element. For instance, you could set a donation input field to have a value of 50 to start. The user could change it if they wanted, but by default they would be donating $50.
  • pattern - This is where you can enforce a specific pattern. For instance, you could require a phone number to conform to the (xxx) xxx-xxxx format. This pattern accepts a regular expression as its value. This means you can be very specific about how you want your data to be laid out.
  • min - You can use this to specify a minimum value of any numeric input. For instance, an age field should probably have a min of zero.
  • max - Just like min, max is used on numeric inputs. It specifies the max number that can be entered (shocking, I know).
  • step - This is useful for numeric inputs that use some type of picker control. For instance, the range slider or the numeric box with the up/down arrows. The step attribute indicates what value to increment or decrement the value by.
  • required - This is an important one. It says that the field specified is required for the form's data to be complete. In most cases, this means that the form will not submit without this field being filled in. This is also an interesting attribute in that it does not need a value. You just specify the attribute by itself (required). You may see some people put required="required". This is also valid syntax and is used primarily for older browsers.
  • placeholder - This will put data in your input that shows the user what to put in the field. Typically this is grey text instead of black to give an indication that this is not real data. A case where this might be used is in a name field. Some users might be confused as to whether they should put their first or last name in the field but you want both. You could use the placeholder attribute to specify "John Doe". They would see that and know you are asking for first and last name. Once they put their cursor in the box, the placeholder text goes away.
  • maxlength - This is used on text inputs to specify how long they should be. For example, if your database only accepts names up to 100 characters long, you could (and probably should) put a maxlength attribute of 100 on your input field to ensure you don't get more than that. Let the user figure out what to no include.
  • autocomplete - This attribute allows you to turn off the auto-filling of fields on your form. If you specify "off" for this attribute, applications that automatically fill in data will skip this field.
  • autofocus - Use this attribute (with no value) on one element on your page if you want the focus to be on a specific input when the page loads.

Building a Form

Let's put all of this information that we have learned into improving our example form. We are going to beef it up a bit by adding a couple of extra inputs for phone number, user age, email address and graduation date. That should make things a bit more interesting. First, here is what it looks like:

Image 2

Now, here is the code:

HTML
<form role="form" name="userform" action="formprocessor.php" method="post">
    <p>
        First Name: <input name="firstName" type="text" placeholder="John" maxlength="50" required/>
    </p>
    <p>
        Last Name: <input name="lastName" type="text" placeholder="Doe" maxlength="50" required />
    </p>
    <p>
        Age: <input name="age" type="number" min="0" max="140" required />
    </p>
    <p>
        Email: <input name="email" type="email" placeholder="John.Doe@gmail.com" />
    </p>
    <p>
        Graduation Date: <input name="graduationDate" type="date" />
    </p>
    <p>
        Over 18: <input name="over18" type="checkbox" />
    </p>
    <p>
        <button name="process" type="submit">Process</button>
        <button name="clear" type="reset">Clear</button>
    </p>
</form>

See all of the ways we can lock in our input, tailor our user experience and generally make a form that is more pleasant to work with from the user's perspective and from ours on the back-end?

Conclusion

Building forms in HTML is not a difficult thing to do, as we have seen. However, there are a lot of powerful options provided to us that allow us to take our forms to the next level, especially in HTML5. With what we have seen in this article, there is no reason why you can't jump right in and get started building your own forms today.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)