Click here to Skip to main content
Click here to Skip to main content

Beginner's Guide to HTML5 and CSS3 - Formidable Forms with HTML5 (Series 6 of 12)

, 18 Apr 2014
Rate this:
Please Sign up or sign in to vote.
All about HTML5 Input types, Form Element and Attributes. We will be building a form based on HTML4 and 5 form elements.

Introduction

In this article we will be focusing on the below mentioned topics. Let us get started with the basics and then go in detail about the HTML5 form elements, attributes etc. In the end we will be building the sample form which will make use of the HTML5 elements.

At the end of the article you should be able to understand the HTML4 and 5 input elements and build a screen containing a form and make use of a suitable form input elements.

Background

If you are a beginner , it's highly recommended to read through the following articles to understand more about the HTML and CSS.


Beginner's Guide to HTML5 and CSS3 - Writing Your First Code (Series 1 of 12)

Beginner's Guide to HTML5/CSS3 - Styling Your First Web Page (Series 3 of 12)

Beginner's Guide to HTML5 & CSS3 : Laying Out Your First Web Page (Series 4 of 12)

Beginner's Guide to HTML5 & CSS3 - Getting Fancy with HTML5 & CSS3 (Series 5 of 12)


HTML4 Forms (the basics)

Let us try to recall or learn some basics about HTML4 forms. Form elements define an interactive form. The form control element are used to get the input from the user and post them to server for further processing.

The form acts as a container for all the input types that are defined to accept input from the user so that later it can be submitted to server to process the same.

Generally the form contains the input fields like textboxes , radio buttons, checkboxes etc. Every form in a HTML document must contain a input type = 'submit' button so that the user can submit the data either by hitting the return key or clicking on the submit button.

Here's what happens in a normal scenario. The form gets rendered with all the input fields required for a particular usecase; then the user completes or fill in the required form fields and when the user submits the data by say clicking on the submit button, the client side validation can happen; this is done using javascripts which will validate the form input data and make sure what ever data that has been entered is valid.

If there are no validation errors the form gets submitted and now here's what something interesting happens at server side. After the data gets arrived to server, it will process the data. It might save the user data or can do some other interesting stuffs but in the end the server has to respond back to client with the output or result and that gets rendered back in clients browser.

If you are wondering, how the browser submits or send data to the server, the form data gets transmitted as keyvalue pairs. The name corresponds to the input element name and the value is associated with that input type.

Let us see in brief about the form attributes. The action attribute specifies the URL of the web page which handles the server requests. The form method can be either of these values: GET, POST.

Let us now see how the form data gets submitted to server.

The GET/POST method is what we typically defined to submit the data to server; When you are using GET method, the form data is sent to server as a query string containing name,value pairs.

If the form method is defined with POST, the entire form data is sent transparently to server by making use of HTTP Headers. Note – The form data will be encoded as defined in the form content-type. By default the contents are encoded as application/x-www-form-urlencoded.

When you are using GET method, you can see the form data in the browser URL where the form data will be separated from the URL with a question mark; by default the browser encodes the data which means all spaces or unsafe characters like /,\,=,& and + will be replaced with a hex code to represent them as a character; when the data reaches the server, it will un-encode the same.

When you are using a POST method , the form data will be encoded and sent it across to server within the HTTP Headers so you won't see the in the query string. When it comes to submitting sensitive information, we have to use POST method and send it across under a secure socker layer (SSL) as it will encrypt the data.

Note – An HTML document can have multiple forms but each form must contain an input type with submit in order to send the form data to server.

Now we will see the HTML form elements that can defined and used within a form element.


FieldSet


A fieldset in a form is used to group related form controls into a smaller group. The fieldset improves the usability of the user as it clearly segregates the controls.

Below is an example demonstrates the usage of a fieldset.

<form method="post" action="">
  <fieldset>
    <legend>Contact Information</legend>
    <table>
      <tr>
        <td>
          <label for="name">Name:</label>
        </td>
        <td>
          <input type="text" name="name" id="name">
        </td>
      </tr>
      <tr>
        <td>
          <label for="email">E-mail Address:</label>
        </td>
        <td>
          <input type="text" name="email" id="email">
        </td>
      </tr>
      <tr>
        <td>
          <label for="addr">Mailing Address:</label>
        </td>
        <td>
          <textarea name="address" id="addr" rows="4" cols="40"></textarea>
        </td>
      </tr>
    </table>
  </fieldset>
  <p>
    <input type=submit value="Submit Contact Info">
  </p>
</form>

FieldSet


Let us now see the HTML form attributes.


Action attribute

The action attribute specifies where exactly the form data will be sent when the user submits the form.

The action value can be a relative URL, an absolute URL.

Here’s an example: When the form is submitted, the code behind in the demo.aspx gets called and the form data gets processed.

<form action="demo.aspx" method="get">


Method attribute

Method attributes specifies the HTTP method that will be used to submit the form data. The default value of this attribute is GET.

The method attribute can be set with either of the below mentioned values.

  • GET method submits the form data as a query string.
  • POST method is used when you want the form data to be included within the form body.

Here’s in brief about GET method

The GET method sends the form data to server in a query string. Note – The data and the URL will be separated by a “?” character. There’s a restriction for the GET method, you can submit data upto 1024 characters only. Also you cannot send a binary data like images, word documents etc. by using GET Method.

One should never send any sensitive information using GET method.

Here’s in brief about POST method.

The POST method transfers the form data will be encoded and sent via HTTP headers. Also the POST method does not have any restriction on data size to be sent. You can use the POST method to send ASCII and Binary data.

As the POST data is sent as encoded plain text through the HTTP header. If you want to send some secure information, then you will have to send all the information through Secure HTTP.


EncType Attribute

The enctype attribute is used when you want to encode the form data prior to it being sent to the location as defined in the form’s action attribute. Note – By default the enctype attribute is set to application/x-www-form-urlencoded.

The enctype attribute can be set with any of the following values.

enctype = application/x-www-form-urlencoded | multipart/form-data | text/plain

The default url encoding happens automatically; which means the browser does takes care of spaces and the special characters like apostrophes, percentage and other symbols gets converted to ASCII Hex equivalents. The url encoding replaces all unsafe characters to “%” followed by the equivalent two digit hex decimal.

Note – The multipart/form-data encoding needs to be set when you want upload file using file upload control. What it means is that the form data will be sent across to server as a MIME document.


Accept-Charset Attribute

The accept-charset is used to specify the character encoding that the server can process the input data.

The default value of this attribute is “UNKNOWN” (The encoding equals the encoding of the document containing the <form> element).

This attribute can be set with one or more character encoding. In HTML4 the list of encoding must be separated by commas but when it comes to HTML5, the list must be separated with a space. You can set the character set values to ANSI, ISO-8859-1, and UTF-8 etc.

Note – The default character encoding in HTML5 is UTF-8.

<form action="action.aspx" accept-charset="ISO-8859-1”>


Target Attribute

The target attribute is used to specify where the output of the HTML response that is received after submission of the form should be displayed.

The target attribute can be set with the below mentioned values.

_blank - Used when you want to load the document into a new blank window.

_parent - Used when you want to load the document into the immediate parent of the document the link is in.

_self - Used when you want to load the document into the window in which the link was clicked; nothing but the active window. This is the default value of the target.

_top – Used when you want to load the document into the topmost window.

Example:

After submission of the form, the result be displayed in a new window.

<form method="POST" action="Index.aspx" target="_ blank">  


Name attribute

The name attribute specifies the form name. You can use this one for backwards compatibility. Ideally the applications should use the “id” attribute to identify the element.

Example:

<form action="Index.aspx" name=”indexPage”>

HTML4 input tags

The input tags specifies input elements which can be used to capture data from the user.

Text field

The text field in HTML4 is used for input some text. Note – only a single line of text is allowed. A text field is define using input = “text”

Now let us looks into the attributes that one can apply for a text field.

  • name – Specifies the name of the text field. It is used when submitting the form to the server. Also the name can be used when referencing the form field from JavaScript.
  • value- Specifies the text field value. It is used to set the text value to be displayed in the text field as default text.
  • size – Specifies the approximate size in characters of the text field. Note, the size will not always fit the given number of characters, and it varies by browsers.
  • maxlength – Specifies the maximum number of characters that is allowed to type in a text field.
  • readonly – Specifies the text field in read-only mode. The valid values are true and false. When set to true, you won't be able to change the value of a text field.
  • disabled – Specifies the text field in disabled mode. The valid values are true and false. When set to true you won't be able to change the text displayed in the text area. Also when the form is submitted, the value of the text field won't be submitted.

Here's an example:

<input type="text" value="Email Address" size="20" maxlength="25">

TextArea

The textarea field is used for multiline input. When used, it creates a similar control like the one text field does but the only difference with text area is, it allows multiline. You can make use of this control say to enter address information etc. A text area is defined using <textarea> tag.

Now we shall see the attributes that can be define for a text area.

  • name – Specified the name of the text field. Is used when submitting the form to the server.
  • rows – Specifies the number of text rows the text area should show. Note – The does not restrict the data that one can input. You can still type in more rows, however the number of rows that is being displayed for text area depends on this attribute.
  • cols – Specifies the number of columns (characters) to show.
  • wrap – Specifies the text wrapping mode of the text area.
  • soft – Specified the text is wrapped in browser, but not when submitted to server.
  • hard – Specified the text is wrapped in browser, and also when submitted to server.
  • off – Specifies when no automatic text wrapping is required.
  • readonly – Specifies the text field in read-only mode. The valid values are true and false. When set to true, you won't be able to change the value of a text field.
  • disabled – Specifies the text field in disabled mode. The valid values are true and false. When set to true you won't be able to change the text displayed in the text area. Also when the form is submitted, the value of the text field won't be submitted.

Here's an example: Defines a textarea with rows set to 5 and cols set to 30 with text wrapping(only shown in browser but not submitted to server)

<textarea name="textarea" rows="20" cols="50">This is a TextArea Feild</textarea>

TextArea

Check box

The check box field which gets displayed with a label and a little square. When the box is empty, and you click on the box; that's when the check box is said to be “checked”. You can uncheck it by clicking on the box again. The check box is defined with an input type = 'checked'.

Now we shall look into the properties of a check box.

  • name – Specifies the name of the checkbox. It is used when submitting the form to the server.
  • value - Specifies the value of the check box field. It is used when submitting the form to the server. If the check box is checked , the value field is what gets submitted to server; The value won't be submitted if the checkbox is un checked.
  • checked – When used, the checkbox field is shown as checked. This attribute does not need a value, although you could also define a checkbox field with checked="true".
  • disabled – Specifies the text field in disabled mode. The valid values are true and false. When set to true you won't be able to change the text displayed in the text area. Also when the form is submitted, the value of the text field won't be submitted.

Here's an example of a check box field.

When you click on the check box, the selected checkbox values are submitted to server.

<form>
  <p>Favorite Programming Language</p>
  <input type="checkbox" name="lang" value="C#">C#</input><br>
  <input type="checkbox" name="lang" value="Python">Python</input></br>
  <input type="checkbox" name="lang" value="Java">Java</input>
</form>

CheckBox Group

Radio button

The radio buttons are similar to check boxes which can be used to turn on or off. The two primary differences between a radio button and a checkbox is, when you are using a group of radio buttons where all of them have a same name; in such cases if you can turn on only one of the grouped radio buttons. Which means, say you are selecting a radio button which makes it on; Then you have decided to select some other radio button in the group, the previously selected one will be turned off and the most recent radio button will be turned on.

The other difference is, when you are using a single radio button and selecting the same to make it turned on, you won't be able to deselect or turn off the selection (unless you are making use of javascript to explicitly handle these cases)

When you are providing the user with a multiple options and let the user select one from the group of options, the radio buttons are the most useful form element that can be used.

Now we will look into the attributes of a radio button.

  • name - Specifies the name of the radio button.
  • value – Specifies the value of the radio button. This is used when submitting the form to the server. If the radio button is checked, the value inside the value attribute is submitted. If none of the radio button with in a group is selected, no radio button parameter is submitted to server.
  • checked – Used when you wish to default the radio button selection.
  • disabled – When used, sets the radio button in disabled mode. You won't be able to change the initial state of the radio button. The valid values for this attribute are true or false. Note - when the form is submitted with a disabled attribute, the value of the radio button will not be submitted.

Here's an example:

<form action="Drinks.aspx" name="frmDrinks" method="get">
<p>Please select your favorite drink: </p>
<input type="radio" name="drink" value="Water"> Water<br>
<input type="radio" name="drink" value="Coke"> Coke<br>
<input type="radio" name="drink" value="Pepsi"> Pepsi<br>
</form>

Radio Button Group

Select Box

The select box shows up a list of items so that one can select one or more items. The items with in a select box is defined with an option element. A selected attribute is used to preselect an option with in a select box.

  • disabled – When specified disables the input control.
  • multiple – Specifies that multiple items can be selected at a time.
  • name - Used to assigns a name to the input control.
  • size - Specifies the number of visible items in the drop-down list.

Here's an example:

<p>Select your favorite Programming Language:</p>
<select>
    <option value="1">C#</option>
    <option value="2">Java</option>
    <option value="3" selected>Perl</option>
</select>    

SelectBox

File field

The input type with file is used to browse and select a file to be uploaded to server.

Here's an example: Note – In order for the file input type to work, you need to set the enctype to multipart/form-data.

<form action="Upload.aspx" method="post"
      enctype="multipart/form-data">
    <input type="file" name="File">
</form>

Now we will look into the file field attributes.

  • name – Specifies the name of the radio button.
  • accept – Used to set the mime-type of the files the server will accept. Ex: image/gif or image/*.
  • disabled – When used , it disables the file field. You won't be able to change the initial value of the file field. Valid values are true and false. When disabled the value of the field field won't be submitted to the server.

File Field

Button element

The button in a HTML form defines a submit, reset or a push button.

Now we will see what each of these button types does.

submit – Used to create a button that submits a form when pressed

reset - Used to create a button that automatically resets form controls to their initial values as
they were when the page loaded

button – Used to create a button that is used to trigger a client-side script when the user clicks
that button

Let us take a look into the button attributes.

  • name – specifies the name of the button.
  • value – Used to set the text used on the button.
  • disabled – When set, the button will be in disabled mode. You won't be able to click on the button. The only valid values are true or false.

Here's an example: You can notice here the usage of all three input types: submit, reset, button.

<form action="test.aspx" method="post">
<p>
  <input type="submit" name="btnSubmit" value="Submit">
</p>
<input type="reset" value="Clear form">
</p>
<p>
<input type="button" value="Alert" onclick="alert('CodeProject')">
</p>
</form>

HTML5 Input Types

HTML5 introduces handful of new controls which is required in our modern web applications which can be used to input data from various devices like mobile, tablets, desktops. There's a significant benefit in using new controls one is less development time and the other benefit with the usage of new controls is better user experience.

Let us see some of the advantages of using HTML5 input types.

1. The new input types cuts down the client side scripting for validating common data types like dates, email addresses, and URLs.

2. In case of mobile pages, creating a cross platform web page by using HTML5 input types creates a consistent user interface, less custom code and more easy to develop.

3. Forms written with HTML5 can utilize the mobile device’s native specialized keyboards. Depending on input type say the input type is number a numeric keyboard is shown or if the input type is email , a suitable keyboard will be show using which the user can easily key in email addresses.

Now let us see in brief about new controls.

Search

A search field when used will show up the control like a text box. When the user types in some text in search field, you will notice a small cross-mark at the end of the search control which can be used to clear search field.

Although it's not a big deal in using this control but it makes a difference say when you are trying to search something from your phone. In phones like iPhone on focus of search field , will display the keyboard with a search button. You can start using this field right from today if you haven't really used and you don't have to worry about the browser compatibility; if your browser does not support then this field will be displayed as a normal text field.

The search field is defined as below.

<input type="search" name="search">

If you specify a results attribute with a valid positive integer value in search field, you will notice a little search icon on the left side of the control where you can select previous search results. Note the search count will be as specified in the results attribute.

Note – If you wish to persist the search value to be across the pages , autosave attribute with a unique value can be used with in the search field. Also if you wish to apply some styles for the search field you can do as below.

input[type=search] { 
    color: red;  
    cursor: pointer;
    display: block; 
    width: 30%; 
    letter-spacing: 4px;        
    text-shadow: 0 0 2px black;       
    word-spacing: 20px;               
}  

Search Input Type

Email

Now let us try to understand email input type. The email input type is used when you want to allow the user to accept one or more email address. The browser supporting email types will automatically validate for a valid email address and report an error message if the user entered email addresses are invalid. Also when you combine it with validations such as applying required attribute will make sure the email address is always specified.

Note the browser which supports this type will make use of pattern matching to make sure the user entered email address is valid and we don't have to worry about any custom validations on this field.

Here's an example of the usage of email input type.

<form>
    <input type=email name=email>
    <br><br>
    <input type=submit>
</form>            

Email Input Type


Url

The input type url is used is for web addresses. The user can key in one or more url's in the url input type field. The browser supporting url types will use some patterns to validate for a valid url and present the user with a message if the url is invalid.

Here's the usage of url input type.

<input type="url" name="url">

Url Input Type

Tel

The input type tel is used to input a telephone number. The desktop browsers does not guarantee the telephone number validation as the telephone number format various from country to country.
International telephone numbers will be prefixed with plus sign. It is always advised to apply client side , server side validation for telephone type.

Here's an example:

<form action="Index.aspx"> 
  Telephone #: <input type="tel" name="usertel"><br>
  <input type="submit">
</form>  

Number

The input type number creates a control with a up and down and lets the user to press up to increment the number by the specified step and down to decrement the number.

We need to set the below mentioned properties for number input types.

min : Specifies the minimum value for the field
max : Specified the maximum value for the field
value : Intial value or Default value. Note the value is shown only when the page gets loaded.
step : Incremental value stop.

<input type="number" name="age" min="18" max="100" value="18" step="1">

In the above example the number control will be defaulted with the value = 18 and when the user selects up, the number gets incremented by 1.

Number Input Type

Range

The input type range is similar to that of a number input type but the only difference is the range type is displayed as a slider so that the user can either increment or decrement a value by just sliding the control.

In browsers like IE 10 and higher when we are sliding, the range value is shown up as a tool tip. This will help the user to understand the exact value.

Here's an example

<input id="skill" type="range" min="1" max="100" value="0">

Range Input Type

Dates and times

Selecting the datetime in a web form is a common thing we used to either custom code the datetime control using javascripts or use jquery or other third party libraries to accomplish the same. But now with HTML5 there is a built in support for datetime and we don't have to code even a single line or include javascript for date picker.

The date picker support in HTML5 works a similar way the JavaScript Libraries did; when we focus on the field, a calendar will pop out and then we can navigate through the months and years to select the date.

Here's an example of HTML5 Datetime

<input type="date" name="date">
<input type="month" name="month">
<input type="week" name="week">
<input type="time" name="time">
<input type="datetime" name="datetime">
<input type="datetime-local" name="datetime-local">

DateTime Input Type

Color

The HTML input type color shows up a color picker so that the user can select the color from the color picker.

Here's how we define the color types.

<input id="background-color" type="color" /> 

Here's a simple HTML and Jquery code to get the selected color from the color picker.

<!DOCTYPE html>
<html>
<head>
    <title>HTML5 Color Picker </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        $(function(){
            var color      = $('#colorpicker').val();
            var hexcolor = $('#hexcolor');

            hexcolor.html(color);

            $('#colorpicker').on('change', function() {
                hexcolor.html(this.value);
            });
        });
    </script>
  </script>
</head>
<body>
<h3>Color Picker</h3>
    <form action="color_form" method="get" accept-charset="utf-8" class="cf">
        <label for="color">Color</label> <input type="color" id="colorpicker" name="color" value="#ff0000"> <div id="hexcolor"></div>
    </form>
</body>
</html>

Color Input Type

HTML5 Form Elements

Let us learn about HTML5 related form elements.

Datalist element

Datalists are suggested input values for the associated form input field. The datalist is defined with a set of values; which is used as a suggested values and is shown when the user focus the input type and keys in the text or the user can choose one from the list of options. Technically speaking, the datalist items are defined with a set of option elements.

Here's an example of a simple datalist for a search field. Note – here the datalist 'online-stores' is associated with an input type search.

<p>Search our list of online stores:</p>
<input type="search" list="online-stores">
<datalist id="online-stores" style="display:hidden;">
  <option value="Amazon.com">
  <option value="Zappos">
  <option value="BestBuy">
  <option value="Apple Store">
</datalist>

DataList

Keygen element

The keygen element is used in generating cryptographic keys (The public and private key pairs). When the form is submitted to the server here's what it happens; The private key will be stored on the client side as encrypted data stored in browser's keystore) where as the public key is sent to server along with the form data for certificate request. The certificate authority creates a certificate based on the public key and sends it back to the browser.

In summary the purpose of keygen is to provide a secure way to authenticate users.

The following are the keygen attributes

  • challenge – Used when you wish the value of the keygen element to be challenged when the form gets submitted.
  • keytype - Accepts a value rsa, dsa, ec; is a security algorithm of the key.
  • autofocus - When specified the keygen element will automatically gets focused on page load.
  • name – Represents a keygen name.
  • disabled – Represents the keygen markup element is disabled.

Here's an example of HTML code which makes use of keygen to generate keys which can be further used in authenticating a client.

<!DOCTYPE html>
<html>
<head>
    <title>Keygen Tag in HTML5</title>
    <form id="myform" action="test.aspx" method="get">
        Username:
        <input type="text" name="username" />
        <br/>
        Encryption: <keygen name="security" keytype="rsa" form="myform" autofocus />
        <input type="submit" />
    </form>
</head>
</html>

KeyGen

HTML5 output element

The output element represents a result of a calculation.

The “for” attribute is used to specify the relationship between the output element and the other input types which are involved in the calculation.

The form oninput attribute is used to set the output element with the calculation.

Here's an example: where we are summing up the value of two number fields. When the user keys in or makes use of the numeric controls to set the number, the calculation is done accordingly and the result is set to the output element.

<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
    <input type="number" name="b" value="50" /> +
    <input type="number" name="a" value="10" /> =
    <output name="result" for="a b"></output>
</form>

Output Element 1

Here's another example of the usage of output element. Let the user to slide through the sliding control and the skill level is automatically set to the output element.

<form onsubmit="return false" oninput="skill.value = slevel.valueAsNumber">
  <label for="programSkill">C# Programming Skill Level</label>
  <input name="slevel" id="level" type="range" min="0" max="10" value="0"> 
  <output for="skill" name="level">0</output>/10
</form>

Output Element 2

HTML5 form attributes

Now we shall learn some of the new attributes that were added as a part of the HTML5 specification.

Below are the list of HTML5 newly added attributes.


placeholder

The placeholder attribute allows us to set some text so that gets shown or rendered by default when the field is empty and has not received any focus. When it comes to displaying a small piece of text, it is always good to go with placeholders. Also when the user focus on the field and we begin to key in some text, the placeholder gets automatically disappeared.
Note – The placeholders is not a new thing; some of them implemented the same way back with javascripts. Now with HTML5, we don't have to code anything to show up the placeholder text. Although there is no official syntax for styling the placeholder text; however with mozilla one can use -mozplaceholder and with web kit based browsers we can make use of –webkit-input-.

Here's an example on how to use placeholder attribute.

​<input type="text" name="userName" id="userName" placeholder="User name must be at least 5 characters">

Placeholder

autofocus

The autofocus as the name indicates it is used to automatically focus on a specific field in a HTML document. Before the HTML5 autofocus the only way we would implement the focus capability is, with the help of javascript; now with HTML5, it's much simpler. We just have to define the autofocus attribute for a field in a HTML document.

Note – All modern browsers do support autofoucs; and we don't have to worry about the browser which does not support as it will simply ignore the autofocus attribute. In case of XHTML5, we have to set the autofocus attribute as autofocus=”autofocus”.

Here's an example which autofocus an input type text.

<input type="text" name="first-name" id="first-name" autofocus>


autocomplete

The autocomplete attribute is used to automatically complete the form inputs based on the earlier or previously input data. This helps the user not to retype the same information over and over. The autocomplete attribute was around since IE5.5 but now with HTML5, it was standardized.

Note – The default implementation of the browser is to automatically fill the form fields. However if you wish the user to enter the form field every time when it is submitted, you will have to set the autocomplete to “off” as mentioned below.

<input type="text" name="UniqueIdentifier" id="UniqueIdentifier" autocomplete="off">


required

The required attribute is used when you wish to make a form element as a required field. Upon submission of the form, the browser automatically validates for the required field and reports a meaningful error so that one can easily fix them.

Note – Currently Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ browsers support the required attribute. By default the error messages are shown as a bubble and as of now none of the browsers except Chrome allows us to style the error bubble.

Here's an example of a required attribute. When used, it expects the user to key in the name in the textbox.

<input type="text" id="name" name="name" required>


pattern

The pattern attribute is used to set the javascript regular expression. It is mainly used for custom validating the form fields. When you require to handle some custom validation for the input types, you can set the pattern attribute so upon form submit, the validation happens and lets the user if there are any issues in the form inputs.

Note – Currently Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ are supporting the pattern attribute.

Here's an example of the usage of pattern attribute where the input type only allows a single or multi digit numbers.

<label>
    Item Number:
    <input pattern="[0-9]+" name="item" type="text" title="Allows single or multi digit numbers."/>
</label>

Pattern

novalidate and formnovalidate

Form input elements gets validated by default when you hit the submit button; unless you have explicitly stated a novalidate attribute in form, that's what we will see now.
The HTML5 novalidate attribute is an empty attribute which can be applied on form element. When applied, it specifies no validations to be happened when the form gets submitted to server.

Here's how we can make use of novalidate attribute.

<form id="myForm" novalidate>
Here is an example of that form in XHTML5:
<form id="myForm" novalidate="novalidate">
The formnovalidate attribute can be applied to form input types. When applied, the form gets submited with no validations. Think of a scenario where you wish to save some data; say you may compose a data, save it and later you wish to submit; in such cases we can use formnovalidate.
Here's an example of the usage of formnovalidate and novalidate attributes.
<form>
<p><label>*Name: <input type="text" required /></label></p>
<p><label>*Street: <input type="text" required /></label></p>
<p><label>*Zip: <input type="text" pattern= "[0-9](5|10)" placeholder="5 or 9 digit zip" title="5 or 9 digit zip" required /></label></p>
<input type="submit" name=submit value="submit" />
<input type="submit" formnovalidate name="save" value="Save Draft" />
<p>* Required field</p>
</form> 


You may ask what is the difference between novalidate and formnovalidate ? Both of them are meant for no validations but here's one thing to understand.

The HTML5 has a built in capability of validating the form inputs upon submission. So if you don't want the entire form validations to happen, you can make use of novalidate attribute.

If you still want the form validation to be happened but in some cases like saving the data temporarily so that can be submitted later, in such cases you can use formnovalidate say on “Save” button. So when you click on save button, no validations will happen and the form data could be saved; but when you click on submit button the actual validations will take place.


Input form

The input form attribute is used when you wish to associate an input type. An use case where you can think of using the form attribute is, say if you want to reuse the input types to more than one form; you can then use form attribute.


Here's an example: You can notice the input types are being applied with form attribute: form1, form2

<form action="form2.aspx" id=”form2”>
</form>
<form action="form1.aspx" id="form1">
   <input type="submit" value="Submit">
</form>
First name: <input type="text" name="fname" form="form1, form2">
Last name: <input type="text" name="lname" form="form1, form2"> 

Input formaction

The input formaction attribute has the same effect as you specify the same in form element. The only input buttons you can specify the formaction is image or a submit button.

The formaction can be a file name or an application where the form data gets submitted.

Here's an example:

 <input type="submit" value="Submit" formaction="Index.aspx">  

Input formenctype

The formenctype attribute specifies how the form data should be encoded when it's submitted to server using POST method. Note – this attribute can only be applied to input type submit or image.

Note – The default value of formenctype is “application/x-www-form-urlencoded” if not specified. The other options are multipart/form-data, text/plain.

Here's an example:

<form action="Index.aspx" method="post">
  First name: <input type="text" name="firstName"><br>
  Last name: <input type="text" name="lastName"><br>
  <input type="submit" value="Submit">
  <input type="submit" formenctype="multipart/form-data"
  value="Submit as Multipart/form-data">
</form>  

Input form method

The input form method attribute can be one of these GET,POST

Note – you can apply form method to input type submit or image only.

Here's an example:

<form action="Index.aspx">  
   First name: <input type="text" name="firstName"><br> 
   Last name: <input type="text" name="lastName"><br> 
   <input type="submit" formmethod="POST"  value="Submit">
</form> 

Input type form target

The input type form target can be either: _blank, _self, _parent, _top. The target is used to specify where to display the response that is received after submitting the data.

Note – you can apply form method to input type submit or image only.

Here's an example:
After submitting the form, you can see the response being displayed in a new window or tab.

<input type="submit" value="Submit" formtarget="_blank"> 

Putting it all together and building a Form

Now we will see how we can make use of HTML4 and 5 elements in building the form. Let us see with few real world samples.

The first sample that we will see right now is all about building a form to capture the pesonal information. Note - We are just coding the HTML document in this sample; the code behind part for processing the form data will not be covered.

So let us try to focus in making use of HTML5 elements effectively in designing our forms. Before we get started with the real world examples, let us run a quick demo of the usage of HTML5 form elements so that will help in understanding how exactly we can make use of new form elements.




Getting Started in Building a Personal Information Capture Data Screen


Let us go with simple use case to capture the basic personal information. We will focus on some of the most common and required fields in capturing the user data.

Our intent is to capture the User name, Email Address, Telephone, Mailing Address, Age, Date of Birth, Weight Info, Home URL, Photo etc.

Let us first try to analyse what controls would be good to use for the above usecase.

Username - We can use a input type = 'text' field with validation and a placeholder.
Email Address - We can make use of an input type = 'email' field.
Telephone - We can make use of an input type = 'tel' field.
Mailing Address - We can make use of TextArea field.
Age
- We can make use of an input type = 'number', set the min and max attributes.
Date Of Birth - We can make use of an input type = 'date' , set the min and max date attributes.
Weight Info - We can make use of an input type = 'range'.
Home
Url - We can make use of an input type ='url'.
Photo - We can make use of an input type = 'file'.

We shall see how to create a form based on the above discussed input types. Here's the sample HTML5 form.

<form name="demo" id="demo-form" method="post" action="#">    
    
<div id="wrapping" class="clearfix">        
    <section id="aligned">
        
      <input type="text" name="name" id="name" placeholder="Your name" 
        autocomplete="off" tabindex="1" class="txtinput">
        
      <input type="email" name="email" id="email" 
        placeholder="Your e-mail address" autocomplete="off" 
        tabindex="2" class="txtinput">
  
          <input id="dob" class="date" type="date" maxlength="524288" 
        name="lblDate" required="" size="20" tabindex="0" title="Date Of Birth" 
        min="2000-01-01" max="2050-31-12" placeholder="Date Of Birth"/>
   
          <input type="number" name="number" id="number" 
        placeholder="Age" autocomplete="off" tabindex="3" class="txtinput">

          <label for="field9">   
                 Weight (Kg)     
          </label>          
     
      <!-- HTML5 range input -->
          <input type="range" class="range" name="test" min="0" max="300" value="50"/>
          <script>
               $(":range").rangeinput();
          </script>

         <input type="url" name="website" id="website" 
        placeholder="Website URL" autocomplete="off" tabindex="4" class="txtinput">
        
     <input type="tel" name="telephone" id="telephone"
         placeholder="Phone number?(optional)" tabindex="5" class="txtinput">
        
     <textarea name="address" id="address" placeholder="Address"
        tabindex="6" class="txtblock"></textarea>
    </section>


    <section id="aside" class="clearfix">    
        <input type="file" name="lblFileUpload" id="field3" required="required">    
    </section>
        
</div>        
<section id="buttons">        
    <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">    
    <input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" 
        value="Submit this!">
    <br style="clear:both;">        
</section>    
</form> 

Here's how the form looks like when you are trying to view the same in browser. Note -You can notice for some of the input controls have an attribute 'required'; which says, the input element is a required field. The placeholder is set with a meaningful text so each time when the form gets loaded, by default the placeholder text gets displayed and when the user focus on the input controls and start typing, the placeholder text gets vanished.

The input type text, email, date, tel, file, url etc are defined in a pretty strait forward way and that's how one has to use the HTML5 input types. But you might notice a difference in the range input type. The way how the range input is rendered is not how exactly the range input used to be. Note - We are making use of jquery tools library so that it modifies the look and feel as it's shown in the below form. All we have to do is, include the jquery tools library as below and include the javascript code with in the script block.

<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>

<script>
    $(":range").rangeinput();
</script> 

We will also have to include a style sheet which is specific to the range control. Here's how we can include the same. You can download the code for the above sample to get the styles.

<link rel="stylesheet" type="text/css" media="all" href="rangeStyle.css">

Here's what happens with the range control. When the page gets rendered, the elements with the class range will be gets altered as below. You can notice a div with a class slider gets added and the input type range gets converted to text and that's how you will see the customized range contains a textbox showing the value. Note - You don't have to worry about what happens if the javascript script is disabled, if so it the range input gets rendered with no styles. You will be still able to see the range control and if the browser does not support, it will be rendered as a text box.

<div class="slider">
    <div class="progress">
    </div>
    <a href="#" class="handle" style="left: 161.75px;"></a>
</div>

<input type="text" data-orig-type="range" name="test" min="100" max="300" value="150" class="range"> 

Let us now build another sample. In this sample we will try to build a simple contact info page.Here's the HTML5 Form, we are trying to build a contact form.

In the below sample you will see the usage of email, tel, url HTML5 form elements. Also notice the placeholder attribute applied for the form input elements.

<form id="contactForm" method="post">
    <h4>Contact Info</h4>
    <div>
      <label>
        <span>Name: (required)</span>
        <input placeholder="Please enter your name" type="text" tabindex="1" required autofocus>
      </label>
    </div>
    <div>
      <label>
        <span>Email: (required)</span>
        <input placeholder="Please enter your email address" type="email" tabindex="2" required>
      </label>
    </div>
    <div>
       <label>
        <span>Telephone: (required)</span>
        <input placeholder="Please enter your number" type="tel" tabindex="3" required>
       </label>
    </div>
    <div>
       <label>
        <span>Website: (required)</span>
        <input placeholder="Url should begin with http://" type="url" tabindex="4" required>
       </label>
    </div>
    <div>
       <label>
        <span>Message: (required)</span>
        <textarea placeholder="Include all the details you can" tabindex="5" required></textarea>
       </label>
    </div>
    <div>
        <button name="submit" type="submit" id="contact-submit">Send Email</button>
    </div>
</form>  



Points of Interest


It's really exiting to build forms with HTML5 form elements. It's a good idea to redesign our existing forms, make use of new form elements and then apply styles and can take advantage of the technology. It's really not hard to understand and use the new HTML5 input controls. As of now there are 13 new input types available for use and modern browsers supports the most. You don't really have to worry about what if the browser does not support. In such cases the input types gets rendered as a normal text box controls.

History

Version 1.0 - Initial draft and release of Formidable Forms with HTML5 - 04/16/2014

License

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

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile
 
Around 9 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.
 
In Brief
 
Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.
 
Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF
 
Software Development
 
Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI
 
Healthcare Domain Experience
 
CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability
 
Others:
 
TTD, BDD
 
Education
 
B.E (Computer Science)
 
CodeProject Contest So Far:
 
1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro
 
2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics
 
3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin
 
4. Intel App Innovation Contest 2013 - eHealthCare - http://www.codeproject.com/Articles/635815/eHealthCare
 
5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Content 2014

Comments and Discussions

 
GeneralVery Good Article for Beginner to HTML5 & CSS3 PinprofessionalPratik Bhuva25-Jun-14 3:31 
GeneralRe: Very Good Article for Beginner to HTML5 & CSS3 PinmvpRanjan.D25-Jun-14 4:02 
GeneralExcellent Post PinpremiumJames Jensen22-Apr-14 2:54 
GeneralRe: Excellent Post PinmvpRanjan.D22-Apr-14 6:41 
QuestionImages PinprofessionalДмитрий Шатера22-Apr-14 0:24 
AnswerRe: Images PinmvpRanjan.D22-Apr-14 6:45 
GeneralRe: Images PinprofessionalDzmitry Shatsera23-Apr-14 3:04 
QuestionThank you PinmemberMember 998481221-Apr-14 18:28 
AnswerRe: Thank you PinmvpRanjan.D22-Apr-14 6:41 
QuestionGreat read PinmemberGuruprasad.K.Basavaraju17-Apr-14 18:14 
AnswerRe: Great read PinmvpRanjan.D18-Apr-14 5:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 18 Apr 2014
Article Copyright 2014 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid