Form validation that is designed to simplify and work seamlessly with Jörn's jQuery Validation Plugin.
Form validation that is designed to simplify and work seamlessly with Jörn's jQuery Validation Plugin. All of the validation routines are designed to match (as closely as possible) those provided by Jörn, so that the browser and server validation routines are in sync with one another.
Custom validation rules you would like to apply remotely.
$validator->rules['name'] = function ($value) {
return ($value == 'Charlie') ? true : false;
}
$validator->set('name', 'required|remote[name]');
Error messages associated with each validation rule. After checking if $validator->certified()
, this will be an empty array if it passes, or contain all the errors if it doesn't. You can customize and add as you see fit.
$validator->errors['name'] = 'Sorry Charlie, try again.';
if ($vars = $validator->certified()) {
if ($vars['password'] != 'sekrit') {
$validator->errors['password'] = 'Enter a sekrit password.';
}
}
A field's array of acceptable values which, if specified here, do not need to be included 'inList'.
$validator->menu['name'] = array('Charlie');
$validator->set('name', 'required|inList');
Pass an array of $values to be validated.
$validator = new Validator($_POST);
This allows you to set individually (or all at once) the validation rules and filters for each form field. The value of every $field you set here is automatically trim()
ed and returned when $this->certified()
.
The name of your form field. If this is an array($field => $rules, $field, ...)
then we loop through each one and call this method ourselves over and over.
Your $field names can be an array by adding brackets to the end eg. 'name[]'. They can also be multi-dimensional arrays such as 'name[first]', or 'name[players][]', or 'name[parent][child]', etc. The important thing to remember is that you must always use the exact name given here when referencing them in other methods.
A pipe delimited set (or an array) of rules to validate and filter the $field with. You can also specify custom messages by making this an array($rule => $message, ...)
. Parameters are comma-delimited, and placed within '[]' two brackets. The available options are:
$validator->rules['rule'] = function($value){ ... }
to determine the validity of a submitted $value. The function should return a boolean true
or false
.$validator->set('name', 'required');
$validator->set('email', 'required|email');
$validator->set(array(
'password' => 'required|alphaNumeric|minLength[5]|noWhiteSpace',
'confim' => array('required', 'matches[password]'),
));
$validator->set('field', array('required' => 'Do this or else.'));
Goes through every field the $validator->set()
, determines if the form has been sent, and picks out any errors.
An array of validated, filtered, and trim()
ed form values for every $validator->set('field')
IF the form was submitted (ie. at least one field has it's $_GET or $_POST counterpart), AND there were no errors. false
if not.
if ($vars = $validator->certified()) {
// process $vars
}
Add the following to your composer.json
file.
{
"require": {
"bootpress/validator": "^1.0"
}
}
<?php
use BootPress\Validator\Component as Validator;
$validator = new Validator($_POST);
The first thing you need to do is give us an array of values to validate against. In this case you have given us the $_POST
vars. Now you can set the rules and filters for each field.
// Create a custom rule
$validator->rules['name'] = function ($value) {
return ($value == 'Charlie') ? true : false;
}
// Customize error messages
$validator->errors['name'] = 'Sorry Charlie, try again.';
$validator->errors['required'] = 'Why I Oughta!';
// Require a name
$validator->set('name', 'required|remote[name]');
// Require an email, and make sure it looks like one as well
$validator->set('email', 'required|email');
// Set multiple fields at once
$validator->set(array(
'password' => 'required|alphaNumeric|minLength[5]|noWhiteSpace', // Using a pipe separated string
'confirm' => array('required', 'matches[password]'), // Using an array of rules and filters
));
// Set and create a custom required message for this one field
$validator->set('field', array('required' => 'Do this or else.')
To see if the $_POST
array you gave us meets all of your requirements:
if ($vars = $validator->certified()) {
// Add another validation layer
if ($vars['password'] != 'sekrit') {
$validator->errors['password'] = 'Enter a sekrit password.';
} else {
// Process $vars
}
} else {
// The form was either not submitted, or there were errors
}
The $vars
returned are all trim()
ed and filtered, ready for you to process as you see fit. From here, the best thing to do is use our BootPress Form Component, but if you have any better ideas then the following will come in useful:
Get the values of the following protected properties:
$validator->set()
for each field.true
or false
if we know whether the form has been submitted or not, and null
if we don't know.false
, or an array of all the validated and filtered values.Whether or not a form $field has been required.
Get the submitted $field(s) value(s) that should be used when displaying the form. These are the same as the $vars = $validator->certified()
. The array feature comes in handy when saving the values to a database.
Either a string, or an array of values depending on the type of $field. If !$validator->submitted
, then the value(s) will be null
.
Get the error message (if any) that should be used when displaying the form.
Validate all of the rules set up for a $field.
foreach ($validator->rules($field) as $validate => $param) {
$attributes["data-rule-{$validate}"] = htmlspecialchars($param);
}
Iterate over a $field's rules and associated error messages.
foreach ($validator->messages($field) as $rule => $message) {
$attributes["data-msg-{$rule}"] = htmlspecialchars($message);
}
Includes Jörn's jQuery Validation code that this component was meant to sync perfectly with.
The jQuery identifier of your form.
The rules and custom messages should be added to each inputs 'data-...' attributes using $this->rules()
and $this->messages()
. Any other fine-tuning can be done here. The $options values must already be json encoded ie. quotes around strings ("string"), brackets for arrays ([]), quoted bools ('false'), etc. The reason for this is because we cannot json_encode functions properly ('function(){}').
$validator->jquery('#form', array('debug'=>'true'));
Get the unique id assigned to a $field.
All of the above is just assuming you are using this component to validate submitted form data, but it is equally well suited to validate anything on the side as well. The static methods we provide (and use ourselves) are:
Determine if the $value is a valid decimal number. Can be positive or negative, integer or float, and commas to separate thousandths are okay.
Validator::number(1.345); // true - this is a number
Validator::number('string'); // false
Determine if the $value is a positive or negative integer number, no commas.
Validator::integer(1000); // true
Validator::integer(1.345); // false - must be a whole number
Determine if the $value is a positive integer number, no commas.
Validator::digits(1000); // true
Validator::digits(1.345); // false - no periods allowed
Determine if the $value is greater than or equal to $param.
Validator::min(5, 3); // true - 5 is greater than 3
Validator::min(3, 5); // false - 3 is less than 5
Determine if the $value is less than or equal to $param.
Validator::max(5, 3); // false - 5 is greater than 3
Validator::max(3, 5); // true - 3 is less than 5
Determine if the $value is greater than or equal to $param[0], and less than or equal to $param[1].
Validator::range(5, array(2, 7)); // true
Validator::range(5, array(6, 7)); // false
Determine if the $value has alpha (a-z), numeric (0-9), and underscore (_) characters only.
Validator::alphaNumeric('abc123'); // true
Validator::alphaNumeric('abc-xyz'); // false
Determine if the $value's length is greater than or equal to $param.
Validator::minLength('string', 2); // true
Validator::minLength('string', 7); // false
Determine if the $value's length is less than or equal to $param.
Validator::maxLength('string', 7); // true
Validator::maxLength('string', 2); // false
Determine if the $value's length is greater than or equal to $param[0], and less than or equal to $param[1].
Validator::rangeLength('string', array(2, 6)); // true
Validator::rangeLength('string', array(7, 15)); // false
Validator::rangeLength(array(1, 2), array(2, 4)); // true - there are between 2 and 4 elements in array(1, 2)
Validator::rangeLength(array(1, 2), array(3, 5)); // false - 2 elements is outside the range of 3 and 5
Determine if the number of $value's words are greater than or equal to $param.
Validator::minWords('one two three', 1); // true
Validator::minWords('one two three', 5); // false
Determine if the number of $value's words are less than or equal to $param.
Validator::maxWords('one two three', 5); // true
Validator::maxWords('one two three', 1); // false
Determine if the number of $value's words are greater than or equal to $param[0], and less than or equal to $param[1].
Validator::rangeWords('one two three', array(1, 3)); // true
Validator::rangeWords('one two three', array(0, 2)); // false
Determine if the $value matches the supplied regex ($param).
// Allows phone numbers with optional country code, optional special characters and whitespace
$phone_number = '/^([+]?\d{1,2}[-\s]?|)\d{3}[-\s]?\d{3}[-\s]?\d{4}$/';
Validator::pattern('907-555-0145', $phone_number); // true
Validator::pattern('555-0145', $phone_number); // false
Determine if the $value is a parseable date.
Validator::date('2015-12-31'); // true
Validator::date('infinite'); // false
Determine if the $value is a valid looking email.
Validator::email('email@example.com'); // true
Validator::email('email@example..com'); // false
Determine if the $value is a valid looking url.
Validator::url('http://example.com'); // true
Validator::url('example.com'); // false
Determine if the $value is a valid looking ipv4 address.
Validator::ipv4('175.16.254.1'); // true
Validator::ipv4('2001:0db8:0000:0000:0000:ff00:0042:8329'); // false
Determine if the $value is a valid looking ipv6 address.
Validator::ipv6('2001:0db8:0000:0000:0000:ff00:0042:8329'); // true
Validator::ipv6('175.16.254.1'); // false
Determine if the $value exists in the $param array.
Validator::inList('2', array(1, 2, 3)); // true
Validator::inList(7, array(1, 2, 3)); // false
Determine if the $value contains any white space.
Validator::noWhiteSpace('whitespace'); // true
Validator::noWhitespace('white space'); // false
Removes any doubled-up whitespace from the $value.
Validator::singleSpace('single space'); // 'single space'
Validator::singleSpace('single space'); // 'single space'
Returns a 1 (true) or 0 (false) integer depending on the $value.
Validator::trueFalse(101)); // 1
Validator::trueFalse('true')); // 1
Validator::trueFalse('n')); // 0
Validator::trueFalse(0)); // 0
Returns a 'Y' or 'N' string depending on the $value.
Validator::yesNo(101)); // 'Y'
Validator::yesNo('true')); // 'Y'
Validator::yesNo('n')); // 'N'
Validator::yesNo(0)); // 'N'
The value you want to validate always comes first, and any parameters come second - lest you be confused.