Html5 Tutorial : Forms

4. Forms

Previously called Web Forms 2.0, HTML5 forms are going to make the creation and validation of forms easier than before.

4.1. What Are The Needs For Web Applications?

  • Web Application use forms to gather input from users
  • For instance, a form allow users to:

    • Leave a comment on a blog article
    • Book a flight
    • Sign in to a web site
    • Etc…
  • Controls that most of Web Applications require are:

    • Email
    • Date
    • Phone number
    • URL
    • Sliders
  • Moreover, often times Web Application also require:

    • Auto focus on an element of the form
    • Give hint to user on what information they should give and how
    • Handling minimum/maximum values for some controls
    • Force the user to enter a value on a form
    • Display error messages to their users

      • When they do not provide required information
      • When the provided information is in the wrong format
    • Validate the form on the client side to prevent sending the form to the server if there are errors on the form
[Note]Note

As a rule of thumb, form validation on the server should always exist anyway since JavaScript can be disabled on some client browser

[Note]Note

All of this is possible to do without HTML5 but it is really cumbersome

4.2. Current Solutions

  • There are a lot of limitations with HTML4, it does not fit Web Applications need today
  • Custom controls that does not exist natively such as date picker or slider are provided using third-party libraries (JQuery, MooTools, etc…)

    • That adds libraries to learn
    • JavaScript might be disabled on some client browsers
  • Validation on the client side is quite complicated for some controls

    • Usage of regular expressions for many common used information (email, url, phone number)

4.3. New Input Types

  • HTML5 comes with new controls to ease the creation of forms
  • There are thirteen new values for the type attribute:

    • <input type="color" />: To choose a color

      Figure 2. Color picker showing up on Opera 11

      images/forms_type_color.png


    • <input type="date" />: To choose a date (year, month and day) with no timezone
    • <input type="datetime" />: Same as choosing a date but include the time (hour, minute, second, fraction of second) but the user cannot change the time zone offset
    • <input type="datetime-local" />: Same as datetime except that the user can change the time zone offset
    • <input type="month" />: To choose only a date and a month
    • <input type="time" />: To choose a time (hour, minute, second, fraction of second)
    • <input type="week" />: To choose a year with a week number for this year

      Figure 3. Date picker showing up in Opera

      images/forms_type_date.png


    • <input type="email" />: To enter an email
    • <input type="number" />: To enter a number. Can be combined with other attributes such as min to define min value, max to define max value and step to define the increment
    • <input type="range" />: Displays a slider

      Figure 4. Slider control in Chrome

      images/forms_type_range.png


    • <input type="search" />: No real difference with a text input except that the display might look different (rounded corners in Safari on the Mac)
    • <input type="tel" />: Looks like a text input except that the purpose is for entering phone number
    • <input type="url" />: Looks like a text input except that the purpose is for providing a URL
[Note]Input types on iOS

Safari mobile on iOS shows different types of keyboard depending on the input type (for instance the dial pad is shown to the user to enter a phone number when using <input type="tel">)

4.4. New Attributes

  • Along with new input types, HTML5 comes with new attributes such as:

    • autofocus: Boolean that give automatically the focus on a control. There should be only one control focused per page
    • placeholder: This attribute allows developers to give a hint to the users on what information to provide (might be an example value for instance)

      <input type="text" id="firstname" placeholder="Type your first name here" />

      would produce:

      images/forms_attr_placeholder.png
    • required: Boolean that specify if a user input is mandatory on a control. If a user tries to submit a form that have an empty input for a control that have the required attribute, the browser will not allow the submission of the form
    • multiple: For instance, <input type="file" multiple> allows a user to send multiple files
    • pattern: A developer use mail type for email or url for URL input but what if a developer want something specific to his/her needs? pattern allows the developer to use a regular expression and value entered by a user will have to match this pattern
    • autocomplete: autocomplete have two values: on and off. Can be applied on the entire form (on by default) and on controls. It can be good to remember previous values entered by users. Developers should consider this attribute carefully (sensitive data such as credit card number should not be remembered ⇒ set to off).
    • min and max: Respectively define minimum and maximum values for controls. That works for number type but can also be applied to other input types such as date
    • step: Define the increment number for number input type. For instance, the following code snippet would only accept the following values(0,2,4,6,8 and 10):

      <input type="number" min="0" max="10" step="2" value="0" />
    • list: To reference a <datalist> element by its id attribute. the <datalist> element contains a list of values.

      <input type="text" list="fruit" />
      <datalist id="fruit">
        <option value="Apple">
        <option value="Banana">
        <option value="Cherry">
      </datalist>

      would produce:

      images/forms_attr_list.png

4.5. Form Validation

  • Form validation can happen in many places:

    • On the client-side using JavaScript to avoid unnecessary round trip between the client and the server
    • On the server-side with any server side language (Java, PHP, ASP.NET and others)

      [Note]Note

      Again, always validate user data on the server-side since JavaScript can be disabled on some clients

  • Verifying that the data entered is in the expected format can be really difficult. To do that, regular expressions are used. Below is for instance a really complicated regular expression to validate email:

    [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
  • HTML5 provides automatic form validation and you can add constraints to your form elements using some of the previously discussed attributes (required, pattern, maxlength, type, min and max that can be combined with step)
  • Here below are some examples of form validation:

    • <input type="email" required/> where required will indicate that a value must be supplied

      images/forms_validation_required.png
    • Moreover, constraint validation depending on the type attribute for url or email expect the value to be in the right format. For instance using <input type="url"> and providing a value which is not a URL would have the following effect:

      images/forms_validation_url.png
    • <input type="number" min="0" max="100" step="5"/> where min and/or max attributes are delimitating the boundaries of a value. step will just allow certain values (here 0, 5, 10, 15, 20, etc…):

      images/forms_validation_num_greater.png images/forms_validation_num_step.png

    [Note]Note

    Form validation can be disabled either on the entire form using the novalidate attribute or the formnovalidate on a <input type="submit"/>

  • Using JavaScript and the constraint API, you can do complex validation for your form. Form elements such as <input> have some properties and methods that can be used in your client-side scripts such as:

    • willValidate property: true for <button>, <fieldset>, <input>, <keygen>, <object>, <output>, <select> and <textarea>
    • validity property: is a ValidityState object containing the validity states of the element (valueMissing, typeMismatch, patternMismatch, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, customError and valid)
    • validationMessage property: Message that describes any constraint failure
    • checkValidity() method: Method that returns a boolean saying if the element satisfy its constraint or not. This method when called on the <form> element will return true if all elements nested in the form are valid
    • setCustomValidity() method: Method that will set the custom error message for an element of the form. An empty error message reset the error message to the default

4.6. Browser Support

  • Each browser has different support for new input types and attributes that are related to HTML5 forms.

  • It is important to know that input types that are not supported on a browser automatically fallback to <input type="text">
  • So far, Opera is the one that has the most complete support

4.7. Quiz

  1. Is validating a form on the server side still a good practice when using HTML5 form validation?
  2. To set a custom error message on a form element, do this:

    element.validationMessage = "custom error message";
    • True
    • False
  3. What are the two ways to disable form validation?