Problem:
Developing a straightforward PHP library for efficient form validation, where rules and field names can be easily passed and errors retrieved.
Answer:
One approach is to implement your own validation class utilizing PHP's built-in filter_var function and custom regular expressions. Here's an example:
<code class="php">class FormValidator { public static $regexes = [ // Define various validation patterns 'date' => '/^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}$/', 'amount' => '/^[0-9]+$/', // ... ]; private $validations, $sanatations, $mandatories, $errors, $corrects, $fields; public function __construct($validations = [], $mandatories = [], $sanatations = []) { // Initialize class properties } public function validate($items) { // Perform validation on array items and return validation result } // ... }</code>
Usage:
<code class="php">$validations = ['name' => 'anything', 'email' => 'email', ...]; $required = ['name', 'email', ...]; $sanatize = ['alias']; $validator = new FormValidator($validations, $required, $sanatize); if ($validator->validate($_POST)) { $_POST = $validator->sanatize($_POST); // Process form submission } else { // Handle validation errors }</code>
This provides flexibility in specifying validation rules and retrieving errors compared to using existing frameworks.
The above is the detailed content of What\'s the Easiest Form Validation Library in PHP for Programmers?. For more information, please follow other related articles on the PHP Chinese website!