Điều mà mình ấn tượng nhất với Laravel chính là thư viện Validate của nó. Thực sự rất sáng tạo, và khi chuyển sang 1 dự án khác không sử dụng Laravel giống như WordPress chẳng hạn, mình muốn tìm 1 thư viện Validate như thế và nó chính là GUMP.
- Github: https://github.com/Wixel/GUMP
GUMP là gì?
GUMP là một thư viện PHP dành cho việc xác minh, kiểm tra dữ liệu (Validate) và lọc dữ liệu (Filter). Nó là 1 thư viện mã nguồn mở được phát triển từ năm 2013.
Cài đặt GUMP vào dự án PHP
chúng ta sử dụng composer để cài GUMP
composer require wixel/gump
Hướng dẫn sử dụng GUMP
Các bạn tham khảo đoạn code 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);
}
Các rule vui lòng tham khảo ở link: https://github.com/Wixel/GUMP
Ngoài ra các bạn có thể dễ dàng mở rộng để validate 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