=====================
Filters On User Input
=====================
Never trust user input. You should always attempt to filter what the user is
sending you in a form. Solar comes with [[Class::Solar_Filter | ]] class to
help with this. There are two kinds of filters: 'validate' filters tell you if
the user input as-is matches a known format, and 'sanitize' filters modify the
user input in some fashion. Solar_Form lets you specify which Solar_Filter
methods you want to apply to each element.
--------
Validate
--------
What if the user enters something besides an email address? It would be
nice if we could get display a message if the data is not valid. We can
do so using the [[Solar_Form::validate()]] method.
First, we need to add a validation filter on the 'user_email' element. This
just tells the form which [[Class::Solar_Filter | ]] method to use; it does
not perform the validation just yet.
{{code: php
// Set the "user_email" element
$form->setElement('user_email', array(
'type' => 'text',
'label' => 'Email Address:',
));
// add a validation filter on the element
$form->addFilter('user_email', 'validateEmail');
// add a validation filter wich requires parameters
$form->addFilter('user_email', array('validateMinLength', 6));
}}
Then, after populating the form object with data, call the
[[Solar_Form::validate()]] method.
{{code: php
// ... start Solar, create the form object, set elements,
// and then:
$form->populate();
$form->validate();
// ... create a Solar_View object, assign, and display.
}}
Invalid user input (e.g., entering "not really email") will generate the
following output. The feedback messages are added automatically when
[[Solar_Form::validate()]] is called.
If the user input is valid, when you display the form, the list-block
above will be ...
{{code: html
}}
The different "success" and "failure" CSS classes allow you to style
feedback messages appropriately.
--------
Sanitize
--------
Sometimes we will want to process the user input in addition to validating it.
What if the user had extra spaces before or after the email address? Those
spaces will confuse the validation, even though it looks (to the user) like a
valid address. For these and other cases, you can add a 'sanitize' filter to
an element to indicate that the user input should be passed through a
[[Class::Solar_Filter | ]] method, removing anything that doesn't pass the
filter.
For example, to trim spaces from the user input before
validation, you can add this filter:
{{code: php
// Set the "user_email" element
$form->setElement('user_email', array(
'type' => 'text',
'label' => 'Email Address:',
));
// add a filter to trim spaces from the address
$form->addFilter('user_email', 'sanitizeTrim');
// *now* add a filter to validate it
$form->addFilter('user_email', 'validateEmail');
}}
All filters are applied in order when you call [[Solar_Form::validate()]], so
you can mix and match sanitize filters with validate filters.