Input Validation
Table of contents
- Overview
- Instance Variables
- Support Functions
- Validator Callbacks
- A. alpha()
- B. alphaNumeric()
- C. between()
- D. classExists()
- E. colonNotation()
- F. different()
- G. dotNotation()
- H. email()
- I. ip()
- J. integer()
- K. isPortUsed
- L. list()
- M. lower()
- N. match()
- O. max()
- P. min()
- Q. negative()
- R. noSpecialChars()
- S. notReservedKeyword()
- T. number()
- U. numeric
- V. required()
- W. positive()
- X. queue()
- Y. special()
- Z. tel()
- A1. testFilterNotation()
- A2. unique()
- A3. upper()
- A4. url()
- Include Deleted
- Composite Field Validation
1. Overview Table of Contents
Validation for console and forms as supported by the HasValidation trait. You can use the chain the available functions or provide them as string input to the argOptionValidate and prompt functions of the Console class. Technically, you can chain them to the choice and confirm functions but it’s not advisable.
2. Instance Variables Table of Contents
protected array $errors
Contains a list of error messages.
protected string $fieldName
The name of the argument or option that is currently validated. Use this if you have multiple inputs for your command.
protected array $reservedKeywords
Supports ability to avoid input that may conflict with a reserved keyword.
The list of reserved keywords is as follows:
protected array $reservedKeywords = [
// Reserved keywords
'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch',
'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do',
'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach',
'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final',
'finally', 'fn', 'for', 'foreach', 'function', 'global', 'goto', 'if',
'implements', 'include', 'include_once', 'instanceof', 'insteadof',
'interface', 'isset', 'list', 'match', 'namespace', 'new', 'or', 'print',
'private', 'protected', 'public', 'readonly', 'require', 'require_once',
'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use',
'var', 'while', 'xor', 'yield',
// Predefined class names
'self', 'parent', 'static',
// Soft reserved / predefined constants
'null', 'true', 'false',
// Predefined classes worth avoiding
'stdclass', 'exception', 'errorexception', 'closure', 'generator',
'arithmetic error', 'typeerror', 'valueerror', 'stringable',
// Enum related (PHP 8.1+)
'enum',
// Fiber related (PHP 8.1+)
'fiber',
];
protected array $validators
A list of currently used validator callback functions.
3. Support Functions Table of Contents
public function addErrorMessage()
Adds a new error message to the $errors array.
Parameter:
string $message- The error message to be added to the $errors array.
public function displayErrorMessages()
Displays a list of all error messages.
public function fieldName()
Sets name of field to be validated.
Parameter:
string|array $fieldName- The name of the field to be validated.
public function setValidator()
Adds validator to array of validators to be used.
Parameter:
callable $validator- The anonymous function for a validator.
protected static function tokens()
Split on commas (tolerate spaces), normalize to lowercase, drop empties. Useful for cases where you have a comma separated string.
Parameter:
string $data- Comma separated strings of values to be converted into an array.
Returns:
array- An array containing values originally found in comma separated string.
protected function validate()
Calls validator callbacks. This function also ensures validators don’t bleed into next question if instance is reused.
Parameter:
mixed $response- The user answer.
Returns:
bool- True if validation passed. Otherwise, we return false.
4. Validator Callbacks Table of Contents
A. alpha()
Enforce rule where input must contain only alphabetic characters.
B. alphaNumeric()
Enforce rule where input must be alphanumeric characters.
C. between()
Ensures input is between within a certain range in length.
Parameter:
array $range- 2 element array where position 0 is min and position 1 is max.
Usage:
// FrameworkQuestion
$question->between([5, 10])->ask($message);
// Array parameter
['between:5:10']
D. classExists()
Checks if class exists within the specified namespace.
Parameter:
string|array $namespace- A string or an array containing one element with string for the namespace.
Usage:
// FrameworkQuestion
$question->classExists(self::SEEDER_NAMESPACE)->ask($message);
// Array parameter
$attributes = ['classExists:'.self::SEEDER_NAMESPACE];
E. colonNotation()
Ensures response is in colon notation format.
F. different()
Enforce rule where response and $match parameter needs to be different.
Parameter:
mixed- The value we want to compare.
Usage:
// FrameworkQuestion
$question = new FrameworkQuestion($this->input, $this->output);
$message = "Enter a value:";
$response1 = $question->ask($message);
$message = "Enter a different value";
$response2 = $question->different($response1)->ask($message);
// Array parameter
$response3 = Controller::prompt($message, $this->question(), ["different:$response1"]);
G. dotNotation()
Ensures response is in dot notation format.
H. email()
Ensures input is a valid E-mail address.
I. ip()
Enforce rule where input must be a valid IP address.
J. integer()
Enforce rule where input must be an integer.
K. isPortUsed()
Checks if a port on a particular host is in use. Assists in verifying if a port is available for a serve command. If the port is already in use an error message is presented to the user.
Parameter:
array $attributes- An array that assumes index 0 is the host and index 1 is timeout variable which is set to 3 if not provided.
Usage:
// FrameworkQuestion
$question->isPortUsed([$host, $timeout])->ask($message);
// Array parameter
["isPortUsed:$host:$timeout"]
L. list()
Ensure user inputs valid comma separated list of values. The user must provide the following in the $attributes parameter: 1) Class containing full namespaced path 2) Name of function that returns an array of strings or a comma separated array of strings. 3) A string value in this array as an alias (optional)
Parameter:
array $attributes- A : separate list in the following format: NamespaceToClass\Class:Method:Alias.
Usage:
// FrameworkQuestion
$question = new FrameworkQuestion($input, $output);
$message = "Enter comma separated list of channels.";
$response = $question->list([
'Core\\Lib\\Notifications\\Notification', 'channelValues', 'all'
])->ask($message);
// Array parameter
$message = "Enter comma separated list of channels.";
$attributes = [
'required',
'notReservedKeyword',
'list:Core\\Lib\\Notifications\\Notification:channelValues:all'
];
Notifications::argOptionValidate(
$channels,
$message,
$this->question()
$attributes, true
);
M. lower()
Enforces rule when input must contain at least one lower case character.
N. match()
Enforce rule where response and $match parameter needs to match.
Parameter:
mixed- The value we want to compare.
Usage:
// FrameworkQuestion
$question = new FrameworkQuestion($this->input, $this->output);
$message = "Enter a value:";
$response1 = $question->ask($message);
$message = "Confirm value entered";
$response2 = $question->match($response1)->ask($message);
// Array parameter
$response3 = Controller::prompt($message, $this->question(), ["match:$response1"]);
O. max()
Ensures input meets requirements for maximum allowable length.
Parameter:
int|array $maxRule- The maximum allowed size for input.
Usage:
// FrameworkQuestion
$response1 = $question->max(50)->ask($message);
// Array parameter
['max:50']
P. min()
Ensures input meets requirements for minimum allowable length.
Parameter:
int|array $minRule- The minimum allowed size for input.
Usage:
// FrameworkQuestion
$response1 = $question->min(5)->ask($message);
// Array parameter
['min:5']
Q. negative()
Enforces rule when input must be a negative number.
R. noSpecialChars()
Enforces rule when input must contain no special characters.
S. notReservedKeyword()
Enforce rule when reserved keywords should be avoided.
T. number()
Enforces rule when input must contain at least one numeric character.
U. numeric()
Enforce rule where input must contain only numeric characters.
V. required()
Ensures required input is entered.
W. positive()
Enforces rule when input must a positive number.
X. queue()
Validates if queue exists in database or redis.
Y. special()
Enforces rule when input must contain at least one special character.
Z. tel()
Ensures phone number is in the correct format.
A1. testFilterNotation()
Ensures response is in colon notation format.
A2. unique()
Enforces rule when input must be a unique value. Checks database and displays message if field with value already exists.
Parameters:
string $modelName- The name of the model we will use for our query.bool $includeDeleted- Enforce uniqueness among deleted records.array $additionalFieldData- Use multiple fields when testing for uniqueness.
Example:
$this->runValidation($this->unique([
self::class, true,
])->fieldName('username')->min(6)->max(150)->validate($this->username));
In the example code above we provide the model, the field to be checked for uniqueness, and we provide a true value to the $includeDeleted field to check for uniqueness among soft deleted records.
Example:
$this->runValidation($this->unique([
self::class, false, ['email' => $this->email, 'fname' => $this->fname]
])->fieldName('username')->min(6)->max(150)->validate($this->username));
In the example above we check multiple fields for determining uniqueness. Here we test username and address.
Short-form Example:
$this->runValidation($this, 'username', [
'min:6',
'max:150',
'unique:'.self::class.":true:email|{$this->email},fname|{$this->fname}"
]);
A3. upper()
Enforces rule when input must contain at least one lower case character.
A4. url()
Enforce rule where input must be a valid URL.
5. Include Deleted Table of Contents
This feature is for form validation operations when you want to test against deleted values. To use this feature call the publicly available includeDeleted() function. Parameters are described below.
Parameters:
param bool|string $includeDeleted- The includedDeleted flag. When true the ‘includeDeleted’ element with a value of true is added to the $queryParams associative array.array $queryParams- The parameters for the query that is passed by reference.
6. Composite Field Validation Table of Contents
The Chappy.php framework supports composite validation rules — where more than one field is used to determine uniqueness. Use the publicly available compositeFieldValidation function. To test against soft deleted items use the includeDeleted function. Parameters are described below.
Parameters:
array|string $additionalFieldData- Additional fields and values to test.array $conditions- The conditions array passed by reference.array- $bind The binds array passed by reference.