InputValidator Documentation

gneustaetter edited this page Jan 25, 2012 · 3 revisions

Input Validator

InputValidator is a validator for form or other user input. The library is easy to include (it's a single file) and provides a fluent interface to reduce the amount of code you need to write to validate user input. In addition to validation methods, InputValidator provides a few filters to convert data to the formats you need. Here's a simple example:

<?
require('InputValidator.php');
// this could be from $_POST
$data = array(
	'name' => 'Greg Neustaetter',
	'email' => 'greg@emailaddress.com',
	'website' => 'http://www.gregphoto.net',
	'favoriteNumber' => 'xyz',
	'date' => '11/11/2011'
);

// pass in the data to be validated
$v = new gUtils\InputValidator($data);

// validate each field
$v->field('name')->required()->length(3,50);
$v->field('email', 'Email Address')->required()->email();
$v->field('website')->url();
$v->field('favoriteNumber', 'Your favorite number')->intRange(0,100)->toInt();
$v->field('date')->toDateTime('m/d/Y')->after(time()); // after the current time

if(!$v->allValid()) {
	echo '<pre>';
	print_r($v->getErrors()); // returns an array of errors indexed by field
	echo '<pre>';
	exit();
} 
$data = $v->getValues(); // returns an array of values indexed by field
$name = $v->get('name'); // get the value of name
echo $v->escape('name'); // escape the value of name for output with htmlspecialchars

Because two of the fields are invalid, this script will print something like the following:

Array
(
    [favoriteNumber] => Your favorite number must be an integer between 0 and 100
    [date] => Date cannot be before 12/24/2011
)

Getting Started

  • __construct ($inputArray=array(), $trimAll=true) - the constructor takes two optional arguments. An associative array of values, indexed by field name, and the trimAll option. If trimAll is true (the default), all values will have the trim() filter automatically applied. If an input array is not provided, then initial values should be provided via the field() method.
  • InputValidator field ($key, $displayName=null, $value=null) - kicks off the validation and filtering for a field, returning the InputValidor instance to allow for chaining of validators, filters, and accessors. If a display name is not provided then InputValidator will use the field key and uppercase the first character. If a value array wasn't passed to the constructor, then you can pass a value here. If a value array was passed to the constructor, but the specified key wasn't included in the array, an empty field will be added and can be used for validation.

Validators

All validators are run against the last field that was added to the validator. If a validator fails for a field, all subsequent validators for that field are skipped. All validators return the InputValidator instance, allowing you to chain validators and filteres. Most validators take additional arguments, and all validators take an optional error message. If you don't provide an error message then you'll get the default error message with the field display name included.

Here's the current list of validators:

  • required($default=null, $errorMsg=null) - fails on empty string and null values. Optionally takes a default value which should be used for the field if it is empty.
  • length ($min, $max, $errorMsg=null) - validates the string length and takes a required minimum and maximum length.
  • noControlChars($errorMsg=null) - validates that the string doesn't include ASCII characters 0-31 (note: values with tabs and new lines will be considered invalid)
  • email ($errorMsg=null) - validates email address
  • url($flags=null, $errorMsg=null) - validates a url, accepting any flags supported by filter_var's FILTER_VALIDATE_URL
  • ip ($flags=null, $errorMsg=null) - validates an IP address, accepting any flags supported by filter_var's FILTER_VALIDATE_IP
  • float ($flags=null, $errorMsg=null) - validates a float, accepting any flags supported by filter_var's FILTER_FLAG_ALLOW_THOUSAND
  • boolean ($errorMsg=null) - validates a boolean, accepting any value accepted by filter_var's FILTER_VALIDATE_BOOLEAN
  • intRange ($min, $max, $errorMsg=null) - validates an integer between an minimum and maximum value
  • regex ($regex, $errorMsg=null) - validates against a user-provided regular expression using the PCRE format
  • matchField ($otherField, $errorMsg=null) - validates that the field is the same value as the field with the key $otherField
  • in ($array, $errorMsg=NULL) - validates that the value is in the provided array
  • func ($func, $errorMsg=null) - validates the value against a user provided function that takes the value as input an returns true for valid values and false for invalid values. Accepts any function that can be called via call_user_func, including a function name, a static method, and instance method, or an anonymous function / closure.
  • before ($value, $format='m/d/Y', $timezone=null, $errorMsg=null) - validates that the field is a date before the date $value in the provided format and timezone.
  • after ($value, $format='m/d/Y', $timezone=null, $errorMsg=null) - validates that the field is a date after the date $value in the provided format and timezone.
  • dateRange ($start, $end, $format='m/d/Y', $timezone=null, $errorMsg=null) - validates that the field is a date between $start and $end in the provided format and timezone.
  • afterField ($fieldName, $errorMsg=null) - validates that the field is a date after the date in the field specified by $fieldName
  • beforeField ($fieldName, $errorMsg=null) - validates that the field is a date before the date in the field specified by $fieldName
  • alpha ($errorMsg=null) - validates that the field contains only letters a-z
  • alnum ($errorMsg=null) - validates that the field contains only letters a-z and numbers 0-9
  • noWhitespace ($errorMsg=null) - validates that the field does not contain any whitespace (spaces, tabs, new lines)

In addition to the individual field validators, InputValidator provides a few methods for validating across multiple fields, mostly via callback functions:

  • formFunc ($func, $errorMsg) - takes a function that receives a single argument, an associative array of field name/values and return true if the validation is successful or false if fails.
  • formAnyFunc ($fieldsList, $func, $errorMsg) - for each of the fields provided in the #fieldsList the provided function will be called, once for each field. The function will receive the value of the field. If the function returns true for any of the fields, the validation is successful. If the function returns false for all fields, the validation fails.
  • formAnyVal ($fieldsList, $val, $errorMsg) - similar to formAnyFunc, but this version passes validation if any of the values are equal to $val, otherwise it fails validation.

Filters

Like validators, filters run against the last field and return the instance of InputValidator, but instead of just validating data, they also change the data. The following filters are provided:

  • trim() - strips whitespace from the beginning and end of the value. Note that all strings are automatically trimmed unless false is passed to the constructor for the option $trimAll (defaults to true)
  • toString() - casts to a string
  • toInt() - casts to an int
  • toFloat() - casts to a float
  • toBoolean - casts to a Boolean
  • filterFunc($func) - changes the value using a user-provided function that accepts the value and returns the new value
  • toDateTime() - converts to a DateTime object
  • toUnixTimestamp() - converts to a Unix timestamp (int)

Checking Validity

After validation has been performed for some or all fields, you can check the validity and get errors:

  • bool allValid() - whether all fields were valid
  • bool valid() - whether the last field to be validated is valid
  • array getErrors - an array of errors indexed by field

Field Accessors

Field Accessors let you get access to the current value of any field. Most of these methods take a $filtered option that is default true. Filtered values are the values after any filters have been applied. Passing false to $filtered will return the original value of the field.

  • array getValues($filtered=true) - returns array of field values index by field name
  • mixed get($name,$filtered=true) - returns the value of the specified field
  • string escape($name,$filtered=true, $flag=ENT_QUOTES) - returns the value of the specified field as a string escaped with htmlspecialchars and the specified flag
  • mixed val($filtered=true) - returns the value of the current field
  • InputValidatorField getCurrent() - returns the underlying InputValidatorField of the current field being validated/filtered
  • array getFields() - returns an array of all of the underlying InputValidtorFields, indexed by field name
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.