Required Values

Mark Birbeck's picture

Many of the forms that we fill in on the web are part of processes that require very specific data. It may be our credit card details or the time of the return flight, but whatever it is, nearly every form we fill in will have values that are required for some operation to complete successfully.

HTML forms don't allow us to specify which form controls must be completed, so there are generally two approaches that are taken. The first is to let the server check for the values after the user has completed the form, and the second is to add some script to the form to check all the required data is present, and prevent sending the data if it isn't.

Of course any significant process on a server is going to have to check the values anyway, but if we don't check the values in the web browser we will have made an unnecessary round-trip to the server, and provided our users with a poor experience.

However, although the alternative of using script improves the user experience, it ultimately suffers from the same problem that we keep coming back to; it relies on a technique that is non-standard, and available only to programmers.

XForms solves this problem by making this functionality available to mark-up authors via a simple attribute that indicates that some particular piece of data is required. The attribute is called required and it sits in the model, on an element called bind.

We'll illustrate the use of this property by indicating in our form that the URL and Description controls must be filled in (i.e., the items called url and description are required data). Before we show how to add these rules, try pressing Save with either of the two controls empty, and you'll see that del.icio.us objects:

Screenshot of the del.icio.us error message.

So, in order to prevent the submission if either URL or Description are empty, update the XForms model as follows:

    <xf:model>
      <xf:submission id="sub-add-link"
       action="http://del.icio.us/api/posts/add" method="get"
      />
      <xf:bind nodeset="url" required="true()" />
      <xf:bind nodeset="description" required="true()" />
    </xf:model>

Once you have added the above mark-up to your form, save and reload, and then try pressing the Save button without filling any data in. As long as one or other of the URL or Title controls are empty, nothing will happen, and you will never be able to post to del.icio.us.

Unfortunately, now if there is an error, nothing happens. In the next section we'll see how to tell our users that something has gone wrong.