Previous chapter | Next chapter
So far, we have created a form with three sections in it: a choice between citizen and company, some questions for the citizen's information and one question for company information. Now we want to make some fields mandatory to be completed by the user.
We had already decorated some elements in our model instance with the required attribute. But generally, we make an XForms control required by creating a binding rule, such as:
<xf:bind nodeset="instance()//citizen_company" required="true()" />
This binding rule would be located in the model in the head section of the HTML. We could add a line, similar to the line above, for each control that is required, or use the required attribute in the instance to do this in one action:
<xf:bind nodeset="instance()//*[@required='true']" required="true()" />
This single line of code will take each of the elements (*) in the instance, for which the required attribute has been set to the value true, and add the binding rule for them. This is a nice way to demonstrate the power of the XForms standard. This approach is convenient, because in this way we keep all the information about the instance in one place - and a side-effect is that the code remains more compact (an extra attribute in the instance versus an extra line for each required element).
There is a bonus to this approach: during development of complex forms, you may want to disable the required aspect of some controls during the process for general testing purposes. By commenting the above code line out, you accomplish just that. Don’t forget to enable this line again before pre-production, though!
The XForms Engine that will actually render the form will probably add some kind of visual symbol such as an asterisk to indicate that the field is required. Of course, this can be styled in many different ways.
If the user would now not enter a value and would want to submit the form anyway, the XForms engine would detect that the required rule has not been complied with and the alert message would be shown. How this is displayed, is up the XForms engine and the styling options it offers.
The client side implementation of this feature varies over providers. Whereas some fire the warning or error message after leaving a field that does not meet the required rule, others only fire a warning or error when a field is emptied.