TUTORIAL: "Form" Class #4: Validating Data - mudmin/UserSpice5-Dev GitHub Wiki
Most often you have very specific ideas of what data you will allow to be placed in your table. And users have a nasty habit of putting the wrong type of data in there unless you require it. That's where validation comes in - making sure that the data entered in your form fully complies with the requirements for the data you are looking for.
The Form class in UserSpice makes uses of the Validate class in UserSpice, so whatever you can do in one can also be done in the other. For more details about the Validate class you should look here.
Assuming that you are familiar with the concepts of validation and have looked over the types of rules available in the UserSpice Validate class, here's an example providing some validation to some of the fields in the form we already created. You can find this form in tutorial/form4.php.
<?php
$fooId = Input::get('id');
$db = DB::getInstance();
$fooData = $db->queryById('foo', $fooId)->first();
$myForm = new Form([
'foo' => new FormField_Text([
'valid' => ['required'=>true, 'min'=>3, 'max'=>5],
]),
'a' => new FormField_Text,
'b' => new FormField_Text([
'valid' => ['is_numeric'=>true],
]),
'bool' => new FormField_Checkbox,
'save' => new FormField_ButtonSubmit,
], [
'data' => $fooData,
'dbtable' => 'foo',
]);
if (Input::exists() && Input::get('save')) {
$myForm->setNewValues($_POST);
$myForm->updateIfValid($fooId, $errors);
$fooData = $db->queryById('foo', $fooId)->first();
$myForm->setFieldValues($fooData); // reload changed values from database table
}
echo $myForm->getHTML();
As you can see, the only change is in these lines:
'foo' => new FormField_Text([
'valid' => ['required'=>true, 'min'=>3, 'max'=>5],
]),
'a' => new FormField_Text,
'b' => new FormField_Text([
'valid' => ['is_numeric'=>true],
]),
The constructor for the FormField_X class takes an argument which is an array. If the key to an element in that array is 'valid' then the corresponding value (an array) allows you to define validation rules.
In this case the field 'foo' is now required (note the change in the icon next to it) and the input in that field must be at least 3 characters long but no more than 5 characters long. The field 'b' is required to be numeric (since it is an integer in the database table this prevents non-numeric inputs being interpreted as zero values).
If you try out various inputs which break the rules (too short or too long or empty on 'foo', non-numeric on 'b') you will see a reasonably worded error message appear at the top of your form and the data will not be saved.
And now you have a fully functional form. The full code of the form is 25 lines long. Let's see if we can't do better than that...
TUTORIAL: "Form" Class #5: Quick & Dirty Forms