Getting Started with ApPHP DataValidator (v2.0.0 or above)
- 1. Common Notices
- 2. Getting Started
- 2.1 Step 1. Creating Validator object.
- 2.2 Step 2. General Settings.
- 2.3 Step 3. Creating ValidatorDataContainer object.
- 2.4 Step 4. Creating ValidationType objects.
- 2.5 Step 5. Customizing ValidationType objects.
- 2.6 Step 6. Validation errors Handling.
- 2.7 Step 7. Localization.
- 2.8 Step 8. Exceptions.
Common Notices
• Use standard opening and closing tags <html>...</html>.
Enclose everything else in these otherwise your page may display incorrectly.
• Do not put ApPHP DataValidator code into another HTML Form: <form>...</form>
Getting Started
Step 1. Creating Validator object.
Make sure you define a valid relative (virtual) path to the Validator.class.php file.
## *** include Validator class define('VALIDATOR_DIR', ''); require_once(VALIDATOR_DIR.'validator.class.php');Class Validator is a basic class which manages a validation process. First of all, you have to create an object of Validator class.
## *** create Validator object $validator = new Validator();
Step 2. General Settings.
You can specify some options for your validator class:
- if you want validation to be stopped after the first error comes up call
$validator->SetStopIfErrorFlag(1); otherwise leave it as a default.
By default validator collects all errors and stops only when there are no more data to validate.
$validator->SetStopIfErrorFlag(1);
-
You can set localization language:
$validator->SetLanguage($language);
where $language is your localization file name (without '.php' extension)
Step 3. Creating ValidatorDataContainer object.
Now you need to set your validating data. By default $_REQUEST array is used, so if you want to use a $_REQUEST array you can skip this part.
If you want to use an array $someDataArray => array($key0 => $value0, $key1 => $value1); as a source for your data, call a method called AddDataContainer:
$someDataArray => array($key0 => $value0, $key1 => $value1); $validator->AddDataContainer($someDataArray);Method AddDataContainer accepts any count of parameters - arrays or objects.
If you want to use an XML file as a data-source, call following method:
$string_xml = '<?xml version="1.0" encoding="UTF-8"?>'; $string_xml .= '<body><name>Jane</name></body>'; $validator->AddDataContainerXml($string_xml);If you want to use JSON instead, call following method:
$string_json = "['name':'jane','age':'20']"; /* or an object with {} */ $validator->AddDataContainerJson($string_json);
Step 4. Creating ValidationType objects.
You are ready now to create ValidationType objects - the entities which contains appropriate data about each validating value. These values could be:
- number (subtypes: integer, float, numeric, hex)
- string (subtypes: alphabetic, alphanumeric)
- URL
- phone number
- IP number
- postcode
- SSN
- one of a set
- function AddEmail($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddIp($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddNumeric($name, $subtype = "numeric", $userFriendlyName = '')
$name is name of your field or value, $subtype is 'int', 'float', 'numeric' or 'hex', $userFriendlyName is used to form an error message - function AddNumericInt($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddNumericFloat($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddNumericHex($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddPhoneNumber($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddPostcode($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddSsn($name, $userFriendlyName = '')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddStringAlphanumeric($name, $userFriendlyName='')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddStringAlphabetic($name, $userFriendlyName='')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddUrl($name, $userFriendlyName='')
$name is name of your field or value, $userFriendlyName is used to form an error message - function AddOneOfSet($name, array $set, $userFriendlyName='')
$name is name of your field or value, $set is an array of possible values, $userFriendlyName is used to form an error message
Step 5. Customizing ValidationType objects.
Every Validation Type has additional options for an agile and accurate validation.
To set these options, simply call a setter method for those you want to use. All methods of validator types return the object of current type. That is we use a pattern "chain-of-responsibility" (read more about a pattern ). This allows to make code simpler and more beautiful.
For example, if there is a key-value pair ["age" => 12] it can be validated like the following:
/* add type to validator with parameter: 1. a key matching the value you validate 2. optional user-friendly name (e.g. 'user age'), used to generate an error message */ $validator->AddNumeric('age', 'user age'); // set validation for a minimum value SetMin(16) // set validation for a maximum value ->SetMax(90) // now the ValidatorType is added and ready to work ->AddType($validatorType) // after you add all required values you can start a validation process $validator->Validate()That's all! Validation is done.
Now you may add any validation types you need with necessary checks. Here is a list of all types and their options:
-
Number (class ValidatorTypeNumeric)
Subtypes:- integer
- float
- numeric
- hex
- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
- function SetMax ($max) value less then maximum
- function SetMin ($min) value more then minimum
- function SetPrecision ($precision_number) number of digits after separator
- function SetPrecision ($precision_number) number of digits after separator
- function SetAllowCommaAsDecimalSeparator ($commaFlag) allow a separator for a float number in string format to be a comma
-
String (class ValidatorTypeString)
Subtypes:
- alphabetic
- alphanumeric
- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
- function SetConfirmationFieldName($fieldName, $userFriendlyName = '') a field value will be compared with value of a confirming field
- function SetConfirmationValue($value) a field value will be compared with a confirming value
- function AddAdditionalElements ($element1, $element2) add any count of special characters to be allowed in you string
- function SetMaxLen ($maxLen) check string length is not more then maximum
- function SetMinLen ($minLen) check string length is not less then minimum
- function SetPointingAllowedFlag ($pointingAllowedFlag) , should be 'true' of 'false': allows or forbids pointing in a string
- function SetRegExp ($regExp) check for a set regular exception
- function SetSpacesAllowedFlag ($spacesAllowedFlag) allows of forbid s space s in a string
- function SetUnicodeAllowedFlag ($unicodeAllowedFlag) allows of forbids unicode to be used in a string
- function SetUppercaseAll() checks if all characters are uppercase
- function SetUppercaseAny() checks if at least one character is uppercase
- function SetUppercaseCount($count=1, $beginWith=0) sets uppercase to be checked in substirng begiingin with $beginWith and for $cont sings
- function SetLowercaseFlag() checks if all characters are lowercase
-
Email (class ValidationTypeEmail)
Validations- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
- function SetConfirmationFieldName($fieldName, $userFriendlyName = '') a field value will be compared with value of a confirming field
- function SetConfirmationValue($value) a field value will be compared with a confirming value
-
URL (class ValidationTypeUrl)
Validations- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
-
Phone number (class validatorTypePhoneNumber)
Validations:- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
- function SetCellPhoneFlag ($cellPhoneFlag): if you want to check specifically for a cell phone number set this flag to "On" (call it with parameter "true")
-
IP number (class ValidationTypeIp)
Validations- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
-
Postcode (class ValidationTypePostcode)
Validations:- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
- function AddCountries (country1, country2), any count of countries canbe added
-
SSN (class ValidationTypeSsn)
Validations:- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
-
One of set (class ValidationTypeOneOfSet)
Validations:- function IsRequired($requiredFlag) if a field is not required, it can be null, 0, '' or 'null' even although those values are not possible by other validations.
Step 6. Validation errors Handling.
Once validation is finished you need to understand if there where any errors. Call a method:
$check = $validator->GetHasErrorStatus();
$check is a boolean value that contains a 'true' if there where any errors, or a 'false' if there where none.
If any errors have occurred, you can get them using one of methods:
$errors = $validator->GetErrorArray();
or
$errors = $validator->GetErrorArrayIndexedByField();
In first case $errors is an array of ValidatorError objects (array(ValidatorError $error1, ValidatorError $error2)). Using this array you can get a user friendly messages for every error:
foreach($errors as $error){
echo $error->ToString();
}
In second case $errors contains errors grouped by names (that is - keys from your data container). This array has format: array($name => array(ValidatorError $error1, ValidatorError $error2)).You can use ValidatorError objects to get some additional data about an error (like container array key, minimum value etc.) to do whatever you want it for.
$errorData = array();
foreach($errors as $error){
$errorData[$error->GetErrType()] = $error->GetErrData();
}
In this way you could receive all validation results.
Step 7. Localization.
English is a default language for all validation errors. But it can be easily changed. To do that you have to perform a following steps:
- Make sure you have localization file for a language you want to switch to. This file should be situated in folder "/php_datavalidator/validator_lib/localization/".
- Make sure your file has right name. It can be any name, but it is recommended to use two or three letter language codes (see List_of_ISO_639-1_codes).
- Make sure your file contains all the necessary errors (as in file "en.php").
- In file "/php_validator/validator_lib/config.php" change value of constant "VALIDATOR_LANGUAGE" to your
localization file name (minus '.php' extension)
or
call method SetLanguage of class Validator$validator->SetLanguage($language);
where $language is your localization file name (without '.php' extension)
Step 8. Exceptions.
When an unexpected error happens Validator generate exceptions (class ValicatorException). Usually exceptions are being thrown, but Validator makes it possible to control them. There are thee ways to handle an exception:
- it can be thrown and caught somewhere outside Validator
- it can be written to a log file
- it can be written to exceptions array
$validator->SetExceptionsHandler(ValidatorExceptionHandler::$handler_WriteToArray); $validator->SetExceptionsHandler(ValidatorExceptionHandler::$handler_WriteToFile); $validator->SetExceptionsHandler(ValidatorExceptionHandler::$handler_Throw);or you can set a constant VALIDATOR_EXCEPTIONS_HANDLER in config.php. Possible values are:
- WriteToArray
- WriteToFile
- Throw
$validator->->SetLogFile($logfile);
or you can set a constant VALIDATOR_LOG_FILE in config.php.If you choose a WriteToArray handler, you can get array with method
$validator->GetExceptionsArray();
If you have chosen a WriteToFile but it have encountered any problems in writing exceptions to file,
they will be placed in same array, so will be a writing error.
These are the basic steps to handle ApPHP DataValidator.