Thursday, February 11, 2016

Required fields: more subtle than you might think

In forms parlance, a required field is a field which must contain a value, or else the form will show an error and you won't be able to save it or submit it. This is a pretty fundamental idea, and both XForms and HTML5 even include a way to mark a field as required. Orbeon Forms is no exception and has had support for required fields since the beginning, including in Form Builder.

But what does it mean to contain a value in the context of web forms? Say you enter a few spaces in the field: does this pass validation? Unfortunately, with both XForms and HTML5, the answer is yes, because their definition of a required field is just a field whose value is not the empty string! You might even remember seeing online forms which you can trick into submission (pun intended) by entering a space, or maybe even some fancy Unicode characters, into a required field.

We realized a long time ago that this definition of required was just plain wrong, because in the vast majority of cases the form author really means that the field must contain some non-blank value when the field is required. Providing a few spaces for your name just won't do!

With Orbeon Forms, you can work around the issue by adding a validation formula such as normalize-space() != ''. But this is a bit heavy and we figured that we would address this better in the next release of Orbeon Forms.

We first thought about changing the meaning of required to mean non-blank, or at least to provide that option to the user. But then we realized that most fields do not need to contain leading or trailing spaces. If we were to introduce trimming of leading or trailing spaces for text fields, then the value of a field containing only spaces would automatically become an empty string, and the current notion of requiredness could survive!

So that's exactly what we did. We implemented an option to trim whitespace deep down in our XForms processing engine, and also exposed it nicely to Form Builder. By default, new text and email fields added to a form have leading and trailing space trimming enabled (existing fields are not changed). Further, you can control any field's trimming with the new "Trim leaving and trailing spaces" option in the Control Settings dialog.

When a text field has trimming enabled, its value is automatically adjusted when the field loses focus, such as when you navigate to the next field. If a field contains only spaces, it becomes empty at that time, and shows an error if required.

While we were at it, we made sure that the notion of "space" was inclusive rather than exclusive: we remove not only the ASCII space character, but tabs, any Unicode space characters, zero-length spaces, non-breakable spaces, and even ISO control characters.

We hope you will like this feature, which will be available in Orbeon Forms 4.11.

No comments:

Post a Comment