PHP code example of madesimple / php-form-validator
1. Go to this page and download the library: Download madesimple/php-form-validator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Add the rule to the validator
$validator = new Validator;
$validator->addRule('timezone', function (Validator $validator, array $data, $pattern, $rule) {
foreach ($validator->getValues($data, $pattern) as $attribute => $value) {
if (null === $value) {
continue;
}
if (in_array($value, listTimezones())) {
continue;
}
$validator->addError($attribute, $rule);
}
});
$validator->setRuleMessage('timezone', ':attribute must be an timezone');
// Validate using the new rule
$rules = [
'timezone' => 'present|timezone',
];
$validator->validate($_POST, $rules);
// Add the rule to the validator
$validator = new Validator;
$validator->addRule('model-exists', function (Validator $validator, array $data, $pattern, $rule, $array $parameters) {
// Connect to database
$db = getDbInstance();
list($model, $property) = $parameters;
foreach ($validator->getValues($data, $pattern) as $attribute => $value) {
if (null === $value) {
continue;
}
if (doesModelExist($db, $model, $property, $value)) {
continue;
}
$validator->addError($attribute, $rule, [
':model' => $model
]);
}
});
$validator->setRuleMessage('model-exists', ':attribute must be an existing :model');
// Validate using the new rule
$rules = [
'uuid' => '
// Add the rule to the validator
$validator = new Validator;
$validator->addRule('complex', function (Validator $validator, array $data, $pattern, $rule, $array $parameters) {
foreach ($validator->getValues($data, $pattern) as $attribute => $value) {
if (null === $value) {
continue;
}
$rules['type'] = 'in:alpha,beta';
switch ($value['type']) {
case 'alpha':
$rules['shared_field'] = 'is:int';
$rules['alpha_specific_field'] = 'is:int';
break;
case 'beta':
$rules['shared_field'] = 'in:blue,green';
$rules['beta_specific_field'] = 'is:int';
break;
}
// Apply the type specific rules to this part of the data
$validator->validate($value, $rules, $attribute);
}
});
// No need to define a rule message as only sub-rules can generate errors
// Example usage:
$rulesSet = [
'field' => 'present',
];
// Example Usage
$rulesSet = [
'field' => '
// Example Usage
$rulesSet = [
'field0' => '
// Example Usage
$rulesSet = [
'field0' => '
// Example Usage
$rulesSet = [
'field0' => 'pha,beta'
];
// Example Usage
$rulesSet = [
'field0' => 'pha,beta'
];