Mozilla

Firefox 4: HTML5 Forms

Firefox 4 will come with better support for HTML5 forms. In the latest beta we are experimenting with a set of new features: more inputs types (email, url, tel, search), new attributes (placeholder, autofocus, list), decoupled forms and different validation mechanisms. This is thanks mostly to the hard work of Mounir Lamouri.

Some examples will work in other browsers, but you’ll need Firefox 4 beta to see all of them.

New input field types

In the same fashion as new HTML5 elements, we have new field types to better express what kind of input we want. The look and feel of many of these elements is the same as a text field, but they carry a different semantic meaning. This means that browsers can optimize the experience for users. For example, a mobile browser can provide a specific keyboard for a field. Or the browser can pre-fill phone number fields based on people in your address book. And extensions may even provide some features based on those types.

In this beta, Firefox comes with four new kind of inputs :

<input type="search">
<input type="tel">
<input type="url">
<input type="email">

Of the four new input types, url and email will also validate their content. We’ll talk about that later.

We also have support for a new kind of field:

<output for="i1 i2">

You can use this element to represent an area of the page that reacts to the interaction with a form. Think about the total price in a cart after you’ve changed the quantity of items or the shipping options. It won’t compute anything, you’ll need to do that with JavaScript, but it will give hints to accessibility technologies. The for attribute is a list of IDs of the fields that intervene into the calculation.

Text fields have been improved with <datalist> support. You can easily provide a list of suggestions for a field as the user is typing. You bind the field and the datalist by using the list attribute. It will use every option element inside datalist to populate the list. And for browsers without datalist support, they will display the content of the datalist element. So be sure to provide some valid markup to get a nice fallback.


or

<label>Enter a city: <input list="cities"></label>
<datalist id="cities">
  or
  <label>choose one
    <select>
      <option value="Paris">Paris</option>
      <option value="London">London</option>
      <option value="Berlin">Berlin</option>
      <option value="New York">New York</option>
      <option value="Tokyo">Tokyo</option>
      <option value="Sydney">Sydney</option>
      <option value="Johannesburg">Johannesburg</option>
    </select>
  </label>
</datalist>

New input attributes

Autofocus

When you add this to a field, it will receive focus as soon as possible. The direct advantage for the user is that all sites will have the same algorithm for autofocus instead of relying on different JavaScript code. And browsers or extensions could disable this behavior if a user is not interested in it.

<input autofocus>

Placeholder

The value of this attribute will be displayed inside the form when it is empty and not focused. You can put an example of the kind of expected value.



<label>Telephone: <input placeholder="1-800-555-1234"></label>
<label>Comments: <textarea placeholder="Tell us what you think about our service…"></textarea>

Decoupled forms

You have more options to define the interaction between fields and forms.

form attribute

<input> elements don’t need to be children of a <form> element anymore. You can define them anywhere you want and bind them to a form using the new form attribute. It takes the ID of the form it should bind to.

Here’s an example. Let’s say you’re working on a search engine for some blogging software. You want a very simple form for the general use case and some advanced options if the user needs more control.

At the top of the page you could put:

<input type="search" name="search_field" form="search_form">

And at the bottom:

<form id="search_form" action="search.php" method="post">
  <fieldset>
    <legend>Advanced options</legend>
    <input type="checkbox">Private posts
    <!-- Other options -->
  </fieldset>
</form>

This will behave as if the search field was part of the form. And you get the freedom of placing it wherever you want in your HTML.

Form options on fields

All the options that can be defined at the form level can be overridden at the field element. All submit fields (<button> and input type=”submit”) accept four new attributes : formenctype, formaction, formmethod and formtarget.

One use case could be a form with a preview and post buttons. Each one needs all the fields of the form but they perform a different action.

<form action="new_post.php" method="post">
<label>Title: <input type="text"></label>
<label>Content: <textarea></textarea></label>
<input type="submit" formaction="preview.php" formmethod="get" value="Preview">
<input type="submit" value="Post">
</form>

When the user clicks on the Preview button, its attributes will override the form’s attributes. In this case, instead of a POST request to new_post.php, the whole form will be sent to the preview.php script with a GET method.

Validation mechanisms

One of the big area of improvements for forms is validation. To give the best experience, we need to give feedback as soon as possible to the user. So people have written a lot of JavaScript code to do that. Wouldn’t it be nicer if browsers handled that?

required

By adding this attribute, you’ll mark this field as required. For text fields, it means that it shouldn’t be left empty. For checkbox buttons, it means it should be checked. And for radio buttons, it means one of the button for a group should be selected.

Try each of the examples below and you’ll see that they change color when you interact with them.

<input type="text" required>


<input type="checkbox" required>


<input type="radio" name="radiogroup" required>
<input type="radio" name="radiogroup" required>
<input type="radio" name="radiogroup" required>


url

URL fields are automatically validated.

<input type="url" value="mozilla">
<input type="url" value="http://mozilla.org">



email

Emails are also automatically validated. By passing the multiple attribute (also valid on type=”file”), you can also validate a list of mails separated by commas.

<input type="email" value="foo">
<input type="email" value="foo@bar.org">



<input type="email" multiple value="foo@bar.org, spongebob">
<input type="email" multiple value="foo@bar.org, spongebob@squarepants.org">



pattern

Urls and emails will not be the only type of data you’ll want to validate. Therefore, the pattern attribute will allow you to provide a JavaScript regular expression. This will be matched against the value of the field to determine if it’s valid. You should also provide a title attribute explaining the pattern to the user.

In the example below, try hovering over the text field. You should see a popup that tells you how to fill out the form.

<input pattern="[0-9][A-Z]{3}" title="A part number is a digit followed by three uppercase letters.">


The constraint validation API

If you need even more control over the validation, you can use the setCustomValidity method. If you provide an empty string to this method, the element will be considered valid. Otherwise, it will be marked as invalid and the string will be used as a tooltip to help your user understand the problem.

<label>Password: <input type="password" id="password1" oninput="checkPasswords()"></label>
<label>Confirm password: <input type="password" id="password2" oninput="checkPasswords()"></label>
<script>
function checkPasswords() {
  var password1 = document.getElementById('password1');
  var password2 = document.getElementById('password2');
  if (password1.value != password2.value) {
    password2.setCustomValidity('Passwords should match');
  } else {
    password2.setCustomValidity('');
  }
}
</script>



If one of the field of a form is not valid, then submitting the form will be blocked and the first invalid field will be focused with a message explaining the problem. If you want to override this behaviour and send the form anyway, you can add a novalidate attribute on the form or the formnovalidate attribute on the appropriate submit button.

If you want more details on the validation mechanisms, check out Mounir’s blog post.

New CSS selectors

And to go with all this goodness are a few new CSS selectors.

:required, :optional

All fields are marked as :optional by default. If they have the required attribute, they’ll match the :required pseudo-class instead.

:valid, :invalid

These pseudo-classes represent the state of the field regarding validation. You can use :invalid to override the default styling that Firefox 4 provides.

Here’s an example of a text box where the default style has been overridden.



:-moz-placeholder

This pseudo-class targets input fields displaying a placeholder. This is not yet part of CSS, so you’ll need to use a pseudo-element for WebKit based browsers.

<style>
#selectors2 :-moz-placeholder {
  font-style: italic;
}
#selectors2 ::-webkit-placeholder {
  font-style: italic;
}
</style>
<form id="selectors2">
  <input placeholder="Style me">
</form>

Conclusion

Form features in HTML5 are very new, and there’s still a wide difference between browsers. Opera implemented part of the spec (it was called Webforms2 at that time) so it has decent support for HTML5 Forms, along with some quirks since the spec evolved since that implementation. WebKit-based browsers are currently implementing some parts of the spec so you’ll also find some early support there as well.

We will not be adding more form features in Firefox 4, and there is clearly still some work to get full support for HTML5 forms. New field types (numbers, colors, dates), new attributes (step, min, max), new events (onforminput, onformchange) and so on. We’ll be adding support for more of HTML5 forms in later releases.

This was just a rough introduction. To get all the details, you should go to the documentation on Mozilla Developer Network.

35 comments

Comments are now closed.

  1. mmc wrote on November 11th, 2010 at 12:19:

    This post is not displayed correctly when reading it from planet with Firefox 4 beta 7: The display of page is interrupted just after the first couple of forms, even though I see the rest of the page in view source. For example, the name list at the right of the planet page is not displayed at all.

    1. Anthony Ricaud wrote on November 12th, 2010 at 05:09:

      Oops, sorry for that. One of the tools is transforming <textarea></textarea> into <textarea/> and was causing the error.

      I’ve tried to work around that and I think it is now fixed.

      1. Jeff Walden wrote on November 15th, 2010 at 03:07:

        Doesn’t seem fixed to me (but I do see some of the code you used to try to hack around it, viewing source ;-) ).

  2. Josh wrote on November 11th, 2010 at 12:24:

    I think it’s a shame that the other new form fields aren’t being added yet, because they would have been quite useful.

    But even still, I’m pleased that such brilliant progress has been made. I’m really excited about HTML5 forms; they have the potential to vastly improve interactive experiences on the web.

  3. Peter wrote on November 11th, 2010 at 12:27:

    Nicely done, guys! Been looking forward to these in v4, since I’ve already been implementing them galore. :)

  4. Fred wrote on November 11th, 2010 at 16:38:

    +1
    Current work would make good use of the missing fields, sigh.
    But still I do appreciate the hard work done so far.

  5. Ryan wrote on November 11th, 2010 at 17:41:

    Great to see the awesome progress Mozilla has made with HTML5 Forms chapter in Firefox.

    Is :-moz-ui-invalid/valid going to land in an upcoming beta?

    1. Anthony Ricaud wrote on November 12th, 2010 at 05:17:

      Yes, it should be in the next beta.

  6. SchizoDuckie wrote on November 11th, 2010 at 20:13:

    Awesome! Will there be a native input type=range soon too? We need native sliders in web browsers.

  7. Eli Grey wrote on November 12th, 2010 at 00:08:

    Why are email addresses not validated by default using the RFC 2822 grammar? IPv6 hosts, hosts on non-standard ports, tlds and local hosts (such as n@ai (yes, that’s a real email address)), square brackets (used in conjunction with IPv6 and ports), and countless other legitimate scenarios are not supported.

    1. Richard Milewski wrote on March 17th, 2011 at 11:44:

      It strikes me as odd that DATALISTs don’t work in SELECT elements. Is that a problem with the HTML5 spec, or just an implementation order issue (since much of the HTML5 forms syntax seems to be a work in progress).

  8. Eli Grey wrote on November 12th, 2010 at 00:12:

    Oh, I just read the HTML5 forms spec and see that it’s because of that inadequate grammar required by the spec. Disregard my question.

  9. fflorent wrote on November 12th, 2010 at 00:30:

    I found this odd behavior. This input is validated by Mozilla Firefox :

    Is it normal ?

  10. jpvincent wrote on November 12th, 2010 at 01:57:

    for those who want to start using the HTML5 syntax now, but want to provide the functionalities on all browsers, there is currently only one decent JavaScript library whose goal is to do just that

    I havent tested it on all the new stuff introduced by FF4, but it’s your best choice for now if you want to introduce that into production
    http://code.google.com/p/webforms2/wiki/ImplementationDetails

    on what’s listed in this article, it will emulate in all browsers :
    - placeholder (without the styling)
    - constraint validation
    - validation (without styling)
    - autofocus
    plus number of other stuff FF didnt implemented yet

    1. alexander farkas wrote on November 12th, 2010 at 03:11:

      @jpvincent
      This project (webforms2) is really great, but development was paused in 2008. The script can not handle the partial/bad implementation of webkit browsers (no interactive form validation) and I think, it can’t really handle the partial implementation by FF4.

      You can find a simple test for interactive validation @ http://afarkas.github.com/webshim/tests/submit-test.html#noCapableBugfixes. If you remove the checked state from the first checkbox, the interactive validation will be fixed in webkit. (doesn’t use browser sniffing).

      Zoltan Dulac made a little change, to get this work with chrome (http://www.useragentman.com/blog/2010/07/27/cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets/), but the change isn’t really bullet proof (no feature detection / simple browser sniffing, without knowing, when the bug is fixed by the webkit team). (https://bugs.webkit.org/show_bug.cgi?id=28649)

      @Anthony Ricaud
      The forminput/formchange events aren’t implemented, because there is a discussion about removing them from the spec. (https://bugzilla.mozilla.org/show_bug.cgi?id=605997)

      @Mounir Lamouri
      great work. I wrote yesterday a little script using some of the new Forms, ES5 and CSS3 features of FF4. It makes fun:
      http://jsfiddle.net/trixta/ucVXN/

  11. Genixon wrote on November 12th, 2010 at 06:52:

    hello, how I’m very2x HAppy today because…….????? :P

  12. Marz wrote on November 15th, 2010 at 00:51:

    Is there any way to make the pattern attribute ignore case ?

    I gather from
    http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-pattern-attribute

    that this is as per-the-spec but any insight as to why ignore case wasn’t allowed ?

    Also any reason why the pattern attribute couldn’t be extended to textarea (and maybe then the g + m options of regular expressions) to allow textareas to be validated as well ?

    1. Vitaliy Kupets wrote on November 22nd, 2010 at 07:59:

      you could just use \w symbol to match both cases. If you want to check, whether a string matches some pattern (true/false), you don’t really need a “g” flag.
      Textarea pattern attribute makes sense, I also wonder why it’s not there. In case it will be implemented, the only flag you will eventually really need is “m”, but you can also workaround that by looking for “\n”

  13. fflorent wrote on November 15th, 2010 at 03:54:

    The HTML Code I wrote wasn’t sent. I wrote that if you add an INPUT with type=’URL’, Firefox validates if the user enter “http:mozilla.org” (and that seems to be a strange behaviour)
    http://pastebin.mozilla.org/852446

  14. JO Tosoni wrote on November 19th, 2010 at 06:41:

    Hello,

    Is there any plan to support forms with camera and microphone input, using
    input type=file accept=somemedia/*;capture=somedevice ?

    1. Anthony Ricaud wrote on January 15th, 2011 at 06:25:

      There is some work in progress in that area but that’s not for Firefox 4. https://bugzilla.mozilla.org/show_bug.cgi?id=451674

  15. sarmen wrote on December 15th, 2010 at 15:29:

    i have seen opera doing this same thing. the sad thing is , is that now we have to wait for safari, chrome, and ie to catch up and this setup to become the default on all users computers. its gonna take a real long time :(

    1. Anthony Ricaud wrote on January 15th, 2011 at 06:11:

      HTML5 forms have been invented with graceful degradation in mind. Therefore, you can start using those controls. You’ll get the best behaviour in browsers that support those new functionalities and your forms will still be usable on other browsers.

  16. Jon wrote on January 1st, 2011 at 12:30:

    Does anyone know if HTML 5 will include a REAL COMBOBOX? datalist appears to work more like an autocomplete text box. If an editable combobox isn’t included in HTML 5, THAT IS RIDICULOUS IMHO.

  17. Muhammad Irfan wrote on January 15th, 2011 at 02:32:

    It is amazing what browsers can do now an nowadays. I wish please people will starting using these browsers instead of old browsers like IE 6. It will make life easier for web developers. I also hope other browsers catch up as soon as possible specially IE 9, chrome and safari

  18. grade wrote on February 12th, 2011 at 09:15:

    i’ve tried that mozila can’t view ,
    otherwise opera can do that.

  19. lee wrote on March 4th, 2011 at 01:50:

    bloadware!

  20. Andrea Barghigiani wrote on March 31st, 2011 at 00:42:

    Hi Anthony,
    that’s a really an useful article! I hope you do not mind if I am going to use your article as pattern for an article that I am setting up for my community!

    Right about that, can you tell me if in the Public Release of FF4 did you have added more elements or more functionality to our loved browser?

    I’ve tried to check the spec on Mozilla Developer Network, but the info there looks, more or less, the same.

    Thanks for your help!
    Andrea

    1. Anthony Ricaud wrote on March 31st, 2011 at 06:55:

      Hi Andrea,

      To my knowledge, there are no new features since this blog post in Firefox 4. There were some tweaks and fixes of course but nothing major.

      Please go ahead and translate this. And leave a comment to give us the URL.

      1. Andrea Barghigiani wrote on March 31st, 2011 at 07:55:

        Thank you so much for your help and your kind words! Definitely I’m going to let you know where you can find the translation (will be around half april)!

        By the way… I am trying each of the new functionality that you shown in this article, but at the moment I can’t get to work the datalist element.

        I pasted the code I’m using at this link http://paste.pocoo.org/show/363225/

        There’s something tha I am missing?
        Thanks again!

        1. Andrea Barghigiani wrote on March 31st, 2011 at 07:58:

          btw I am running on the Public release of Firefox (4.0), shall I try with a night build?
          (sorry for the double comment!)

  21. Brian LePore wrote on March 31st, 2011 at 11:17:

    I built support for these a loooong time ago for our form building library. Was really happy to finally see them in Firefox … only issue I found is that the warning message for required messages not filled in upon submit does not scroll with the page. :-p

  22. Si Grady wrote on April 5th, 2011 at 13:37:

    I have an html5 form on my site but in Firefox (all versions) the user cannot select the input box to input data. Only when you send the blank form will the cursor show in the text field through the validation.
    It works as required in other browsers, any ideas please?

  23. florian wrote on April 27th, 2011 at 07:58:

    When I’m using type=url or type=email, etc. FF4 is wrapping the input automatically with a red border/background-shadow style. I don’t want to have this kind of style. Is there a way to deactivate this behavior?

    thx!

    1. Ryan wrote on April 27th, 2011 at 16:19:

      That’s the :invalid pseudo-class just set input:invalid { box-shadow: none; }

Comments are closed for this article.