GUMP – Thư viện Validate mạnh của PHP giống với Laravel
Điều tôi ấn tượng nhất với Laravel là thư viện Validate của nó. Thực sự sáng tạo và khi chuyển sang một dự án khác không sử dụng Laravel như WordPress chẳng hạn, tôi muốn tìm một thư viện Validate như vậy và đó là GUMP.
GUMP là gì?
GUMP là một thư viện PHP để xác minh dữ liệu, kiểm tra (Validate) và lọc dữ liệu (Filter). Nó là một thư viện mã nguồn mở được phát triển từ năm 2013.
Cài đặt GUMP vào một dự án PHP
chúng tôi sử dụng trình soạn nhạc để cài đặt GUMP
composer require wixel/gump
Hướng dẫn sử dụng GUMP
Vui lòng tham khảo đoạn mã hoàn chỉnh sau:
$gump = new GUMP(); // set validation rules $gump->validation_rules([ 'username' => 'required|alpha_numeric|max_len,100|min_len,6', 'password' => 'required|max_len,100|min_len,6', 'email' => 'required|valid_email', 'gender' => 'required|exact_len,1|contains,m;f', 'credit_card' => 'required|valid_cc' ]); // set field-rule specific error messages $gump->set_fields_error_messages([ 'username' => ['required' => 'Fill the Username field please, its required.'], 'credit_card' => ['extension' => 'Please enter a valid credit card.'] ]); // set filter rules $gump->filter_rules([ 'username' => 'trim|sanitize_string', 'password' => 'trim', 'email' => 'trim|sanitize_email', 'gender' => 'trim', 'bio' => 'noise_words' ]); // on success: returns array with same input structure, but after filters have run // on error: returns false $valid_data = $gump->run($_POST); if ($gump->errors()) { var_dump($gump->get_readable_errors()); // ['Field <span class="gump-field">Somefield</span> is required.'] // or var_dump($gump->get_errors_array()); // ['field' => 'Field Somefield is required'] } else { var_dump($valid_data); }
Thể lệ vui lòng tham khảo tại link: https://github.com/Wixel/GUMP

Ngoài ra, bạn có thể dễ dàng mở rộng nó để xác thực các yêu cầu khác.
/** * You would call it like 'equals_string,someString' * * @param string $field Field name * @param array $input Whole input data * @param array $params Rule parameters. This is usually empty array by default if rule does not have parameters. * @param mixed $value Value. * In case of an array ['value1', 'value2'] would return one single value. * If you want to get the array itself use $input[$field]. * * @return bool true or false whether the validation was successful or not */ GUMP::add_validator("equals_string", function($field, array $input, array $params, $value) { return $value === $params; }, 'Field {field} does not equal to {param}.'); /** * @param string $value Value * @param array $param Filter parameters (optional) * * @return mixed result of filtered value */ GUMP::add_filter("upper", function($value, array $params = []) { return strtoupper($value); });
Nguồn: vinasupport.com