PHP code example of cmanley / validate

1. Go to this page and download the library: Download cmanley/validate 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/ */

    

cmanley / validate example snippets



tion save_student_score(array $params) {
	# Create the validator object. By using static, it is only created once and persists for all function calls.
	$validator = new \Validate\Validator([
		'trim' => true, # trim all string values
		'null_empty_strings' => true, # convert empty string values to null
		'specs' => [
			'name'	=> [
				'type' => 'string',
				'mb_max_length'	=> 2,
				'mb_max_length'	=> 30,
			],
			'birthdate' => [
				'type'  => 'string',
				'regex' => '#^[0-3]\d/[01]\d/\d{4}$#', # expect dd/mm/yyyy
				'after' => function(&$value) { # want yyyy-mm-dd
					if (is_string($value) && preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $value, $matches)) {
						$value = $matches[3] . '-' . $matches[2] . '-' . $matches[1];
					}
				},
				'optional' => true,
			],
			'score' => [
				'types'     => ['float', 'integer'],
				'max_value' => 10,
				'min_value' => 0,
			],
		],
	]);

	# Actually validate the parameters. This will throw an exception in invalid parameters are found.
	$params = $validator->validate($params);

	# Insert $params into database here.

}

$error = null;
try {
	save_student_score($_POST);
}
catch (\Validate\Exception\ValidationException $e) {
	$error = $e->getMessage();
}
if ($error) {
	# display error message.
}
else {
	# display success message.
}