Validating form fields
When creating forms, the fields described in the Data types section are used. Regardless of the method of creating a form (from a model / without a model), the fields have properties that are set by default.
- for all field types: required, must_match
- char: regexp, captcha, length, min_length, max_length, min_max_length, unique
- int, float: zero_allowed, positive
- email, phone, url, redirect: format, as well as properties inherited from char
- text: properties inherited from char
- file, image, multi_images: allowed_extensions, allowed_mime_types, as an array
Based on these properties, the initial validation of form fields occurs using the validate().
//Set the fields of the future form
$fields = [
['Name', 'char', 'name', ['max_length' => 20]],
['Coupon code', 'char', 'coupon', ['length' => 8]],
['About me', 'text', 'about'],
['Email', 'email', 'email', ['unique' => true]],
['Password', 'password', 'password', ['min_length' => 5]],
['Repeat password', 'password', 'password_repeat', ['must_match' => 'password']],
['Captcha', 'char', 'code', ['captcha' => 'extra/captcha-simple']]
];
//Create a form object
$form = new Form($fields);
//Set required fields
$form -> setRequiredFields(['name', 'password', 'password_repeat', 'code']);
//Add another field
$form -> addField(['Photo', 'image', 'photo', ['files_folder' => 'uploads']));
//Get data from POST and validate
$form -> submit() -> validate();
//We can check the form state (usually in AJAX)
Debug::pre($form -> getState());
//If the form is valid
if($form -> isSubmitted() && $form -> isValid())
{
...
}
//Selective validation of fields
$form -> submit() -> validate(['name', 'coupon']);
//Adding an error to the form
$form -> addError('Please enter a more detailed description of the activity.');
//Manually setting the field value
$form -> about = 'No activity description specified.';
Thus, when checking fields, the max_length, length, required, min_length, must_match rules will be applied for the corresponding fields. Based on the specific situation, you can redefine the specified rules for fields or assign new ones.
Adding a new rule
To add a new rule, you need to call the addRule() method with an array of parameters in the following order:
- field name, can also be an array or the '*' symbol for all fields
- property name, characteristic of the data type to which this field belongs
- property value to check (if you pass the value in the form '->', then only the message will be changed and the rule will remain the same, this is convenient for changing the error message for fields checked by regular expressions: int, float, email, phone, url, redirect
- message that is displayed if the check is not passed, if this parameter is not passed, a system message for this rule will be displayed
//Making a field mandatory
$form -> addRule('cupon', 'required', true, 'You must enter a coupon code to register.');
//Making all fields mandatory
$form -> addRule('*', 'required', true, 'This field must be filled in.');
//Adding a regular expression check
$form -> addRule('coupon', 'regexp', '/^d+$/', 'The coupon code can only contain numbers.');
//Setting a minimum length for the entered text
$form -> addRule('about', 'min_length', 200, 'You must have at least 200 characters to tell us about yourself.');
//Setting a maximum length for several fields
$form -> addRule(['name', 'cupon', 'email'], 'max_length', 100, 'The field length must not exceed 100 characters.');
//Set a new message when checking for email address uniqueness
//(replaces the default message)
$form -> addRule('email', 'unique', true, 'This email address is already in use by another user.');
//New message when checking for email address correctness
$form -> addRule('email', 'format', '/^[-a-z0-9_.]+@[-a-z0-9_.]+.[a-z]{2,5}$/i', 'Enter a valid email');
//New message (short format) when checking for email address correctness
$form -> addRule('email', 'format', '->', 'Enter a valid email');
//Check for repeated password entry
$form -> addRule('password_repeat', 'must_match', 'password', 'Incorrect password repeat');
//Restriction on uploaded file types
$form -> addRule('photo', 'allowed_extensions', ['png', 'jpg'], 'Select a png or jpg file');
Removing a rule
To remove a rule, you must pass 2 arguments to the removeRule() method: the name of the field and the name of the rule to be removed.
//Do not check the minimum length
$form -> removeRule('name', 'max_length');
//The field is not required to fill
$form -> removeRule('coupon', 'required');
//Fields are not required to fill
$form -> removeRule(['name', 'email'], 'required');
//Remove email uniqueness check
$form -> removeRule('email', 'unique');
//Remove all fields from checking for maximum length
$form -> removeRule('*', 'max_length');
Displaying validation errors
//Entering POST data into the form and validation
$form -> submit() -> validate();
//Get an array of errors
$errors = $form -> getErrors();
//Add an error to the general list
$form -> addError('Error text.')
//Add an error for a specific field
$form -> addError('Error text.', 'content');
//Output all errors in one list
echo $form -> displayErrors();
//Output the form with errors located next to the fields
echo $form -> setDisplayWithErrors() -> display();
Previous section
Setting up form fields