A Laravel-style validation library for WordPress forms.
composer require fiqhidayat/wp-validator
use Fiqhidayat\WPValidator\Validator;
// Create a validator instance
$validator = new Validator([
'name' => 'John Doe',
'email' => 'john@example.com',
'age' => 25,
], [
'name' => 'required|min:3',
'email' => 'required|email',
'age' => 'required|numeric|min:18',
]);
// Check if validation passes
if ($validator->passes()) {
// Validation passed
$validatedData = $validator->validated();
} else {
// Validation failed
$errors = $validator->errors();
}The library supports validating nested arrays and objects using dot notation:
// Complex data structure with nested properties
$data = [
'user' => [
'name' => 'John Doe',
'email' => 'john@example.com'
],
'product' => [
'price' => [
'regular' => 100,
'sale' => 80
]
]
];
// Use dot notation to access nested fields
$rules = [
'user.name' => 'required|min:3',
'user.email' => 'required|email',
'product.price.sale' => 'required|numeric|lt:product.price.regular', // Compare with another nested field
'product.price.regular' => 'required|numeric'
];
$validator = new Validator($data, $rules);This feature works with all validation rules including the comparison rules.
The library also supports validating nested arrays using wildcards:
// Complex data structure with nested arrays
$data = [
'user' => [
'name' => 'John Doe',
'email' => 'john@example.com'
],
'skills' => ['PHP', 'JavaScript', 'HTML', 'CSS'],
'works' => [
[
'company_name' => 'Acme Inc',
'role' => 'Developer',
'start_date' => '2020-01-01'
],
[
'company_name' => 'XYZ Corp',
'role' => 'Senior Developer',
'start_date' => '2022-05-01'
]
]
];
// Define validation rules
$rules = [
'user' => 'required|array',
'user.name' => 'required|string|min:3',
'user.email' => 'required|email',
'skills' => 'nullable|array',
'skills.*' => 'string',
'works' => 'nullable|array',
'works.*.company_name' => 'required|string',
'works.*.role' => 'required|string',
'works.*.start_date' => 'nullable|date'
];
$validator = new Validator($data, $rules);
if ($validator->passes()) {
// All data is valid
} else {
// Get validation errors
$errors = $validator->errors();
}Here's an example of validating a contact form submission in WordPress:
function process_contact_form() {
// Check nonce for security
check_ajax_referer('contact_form_nonce', 'security');
// Get form data
$data = [
'name' => sanitize_text_field($_POST['name']),
'email' => sanitize_email($_POST['email']),
'message' => sanitize_textarea_field($_POST['message']),
];
// Set validation rules
$rules = [
'name' => 'required|min:3',
'email' => 'required|email',
'message' => 'required|min:10',
];
// Create validator
$validator = new Fiqhidayat\WPValidator\Validator($data, $rules);
// Check if validation fails
if ($validator->fails()) {
wp_send_json_error([
'success' => false,
'errors' => $validator->errors(),
]);
}
// Process the form (save to database, send email, etc.)
// ...
wp_send_json_success([
'success' => true,
'message' => 'Form submitted successfully!'
]);
}
add_action('wp_ajax_contact_form', 'process_contact_form');
add_action('wp_ajax_nopriv_contact_form', 'process_contact_form');This library supports most Laravel validation rules including:
required: The field must be present and not emptyfilled: The field must not be empty when it is present (but can be absent)present: The field must be present in the input data (but may be empty)nullable: The field can be null or empty string
string: The field must be a stringnumeric: The field must be numericinteger: The field must be an integerboolean: The field must be a boolean value (true, false, 0, 1, '0', '1')array: The field must be a PHP arraydate: The field must be a valid datejson: The field must be a valid JSON stringtimezone: The field must be a valid timezone
email: The field must be a valid email addressurl: The field must be a valid URLip: The field must be a valid IP addressalpha: The field must contain only alphabetic charactersalpha_num: The field must contain only alpha-numeric charactersalpha_dash: The field may contain alpha-numeric characters, dashes, and underscoresregex:pattern: The field must match the given regular expression
min:value: String/numeric minimum length or valuemax:value: String/numeric maximum length or valuesize:value: The field must match the specified size (string length, numeric value, array count, or file size in KB)digits:value: The field must be a numeric value with the exact length specifieddigits_between:min,max: The field must be a numeric value with a length between the specified min and max
same:field: The field must match the specified fielddifferent:field: The field must be different from the specified fieldconfirmed: The field must have a matching field of {field}_confirmationgt:field: The field must be greater than the specified field (numeric)gte:field: The field must be greater than or equal to the specified field (numeric)lt:field: The field must be less than the specified field (numeric)lte:field: The field must be less than or equal to the specified field (numeric)in:foo,bar,...: The field must be included in the given list of valuesnot_in:foo,bar,...: The field must not be included in the given list of valuesunique:table,column,except,idColumn: The field must be unique in a database table
exists:table,column,where_column,where_value: The field must exist in the specified database tabletable: The database table name (without wp_ prefix)column: The column to check (optional, defaults to the field name)where_column: Additional where condition column (optional)where_value: Additional where condition value (optional)
Examples:
// Check if user ID exists in users table
'user_id' => 'exists:users,id'
// Check if email exists in users table
'email' => 'exists:users,email'
// Check if category exists and is active
'category_id' => 'exists:categories,id,status,active'file: The field must be a successfully uploaded fileimage: The field must be an image file (jpeg, png, bmp, gif, svg, webp)mimes:jpg,png,...: The field must be a file with one of the specified extensionsmimetypes:image/jpeg,image/png,...: The field must be a file with one of the specified MIME typesdimensions:width=value,height=value,...: The field must be an image that meets the specified dimensions constraints
You can extend this validator by creating your own rules. Here's how to create and register a custom validation rule:
// Create a class that implements the Rule interface
class PalindromeRule implements Fiqhidayat\WPValidator\Rule
{
public function passes($attribute, $value, array $parameters, $validator) {
$cleanStr = preg_replace('/[^a-z0-9]/i', '', strtolower($value));
return $cleanStr === strrev($cleanStr);
}
public function message($attribute, $value, array $parameters) {
return "The {$attribute} must be a palindrome.";
}
}
// Register the custom rule
use Fiqhidayat\WPValidator\ValidationExtender;
ValidationExtender::extend('palindrome', PalindromeRule::class);
// Now use it in your validations
$validator = new Validator([
'name' => 'Anna'
], [
'name' => 'required|palindrome'
]);GPL-2.0-or-later