Basic form validation in PHP
-
Include the class located in
FormValidate/Form.class.phpwherever you need the PHP form validator. -
Create the rules array for your existing form:
$rules = [];
$rules["input_name"] = [
"required" => true,
"minlength" => 3,
"maxlength" => 100,
"alphabetical" => true,
"label" => "name",
];Existing rule keys are:
requiredboolean - If set to true, the field must not be empty when submitting the formemptyboolean - If set to true, the field must be empty when submitting the formminlengthinteger - Sets a minimal length for the field valuemaxlengthinteger - Sets a maximal length for the field valuealphabeticalboolean - If set to true, the field must only include alpabetical letters (a-z or A-Z), have a minimal length of 2 and may contain spacesnumberboolean - If set to true, the field value must be numericemailboolean - If set to true, the field value must match an email address.FILTER_VALIDATE_EMAILis used for validationphoneboolean - If set to true, the field value must match a phone number with a length between 3 to 18 characters. The characters can include a+in the beginning-,spaceor parantheses ((and)).labelstring - Sets the label contained in the error message
- Initialize the form validator with the
$_POSTdata and the created rules:
use FormValidate\Form;
$Form = new Form($_POST, $rules);$Form->validate()returnstrueif the validation has been successfully done. If errors occur during the validation,$Form->getErrors()will return anarraywith at least one entry.