sFire PHP Framework

Form Validator

sFire Form Validator lets you easily validate multiple input fields, comes with an arsenal of built-in validator rules and you may also build your own (extending). You can combine multiple fields for validation and set you own custom error messages.

In this section we will handle:

  • Creating a new validator instance
  • Adding form input fields for validation
  • Validating array with multiple input
  • Execute the validation and retrieve the error messages
  • The special required rule
  • All other rules (35 rules)
  • Date formatting
  • Combining fields
  • Custom messages
  • Custom validator functions

Create a new instance

Creating an instance of the validator is as simple as this:

use sFire\Validator\Form\Validator;

$validator = new Validator();

The constructor accepts two optional arguments; prefix and data.

Prefix parameter

The first argument is the prefix and will handle all the field names that are built as an Array like:

<input name="contact[email]">
<input name="contact[address][street]">

Just add the "contact" as prefix and you can point to the input without writing the full name:

$validator = new Validator('contact');
$validator -> field('email');
$validator -> field('address[street]');

Data parameter

By default the global $_POST PHP variable is used for validation data. But you can set your own data to be validated as long as it is an Array.

Adding form input fields for validation

By using the field method, you can add one or more input field names for validation.

$validator = new $validator();

//You can add a single fieldname
$validator -> field('fieldname');

//You can also add multiple fields
$validator -> field('fieldname-1', 'fieldname-2'));

Now you can add one or multiple rules to a field.

Execute validation

sFire Form Validator comes with a arsenal of built-in validation rules. To apply a rule you can do the following:

$validator = new Validator();

//In this example we will use the "email" rule
$validator -> field('fieldname') -> email();

//Fails
if(true === $validator -> fails()) {
    print_r($validator -> getMessages()); //Get the error messages
}

//Passes
if(true === $validator -> passes()) {
    //Validation success
}

Chaining

You may also apply multiple rules by chaining them.

$validator = new Validator();
$validator -> field('fieldname') -> min(0) -> max(6) -> lengthmax(1);

Validating array with multiple input

You can also validate an array of input fields. Imagion that you have a POST variable as an Array with multiple emails. You can validate all the single elements in that Array as email by calling the validateAsArray method.

$input = ['email' => ['john@example.com', 'smith@example.com']];

$validator = new Validator(null, $input);

//Check if field is an Array and that all elements within that Array are valid email addresses
$validator -> field('email') -> validateAsArray() -> email();

Note: this method needs to come before all other rules.

Retrieve all error messages

You can use the getMessages method to return an Array with errors. This method accepts one parameter as a boolean to retrieve the full names or short names of the error fields. This only works when you set the prefix in the validator instance. Default is false (short names).

HTML
<input name="contact[surname]" value="A">
PHP
$validator = new Validator('contact');
$valdiator -> field('surname') -> lengthmin(2);

if($validator -> fails()) {

    $validator -> getMessages(); //Output: [surname: "Minimum 2 characters"]
    $validator -> getMessages(true); //Output: [contact[surname]: "Minimum 2 characters"]
}

Retrieve single error messages

You may also retrieve a single error message:

HTML
<input name="contact[surname]" value="A">
PHP
$validator = new Validator();
$valdiator -> field('contact[surname]') -> lengthmin(2);

if($validator -> fails()) {
    $validator -> getMessage('contact[surname]'); //Output: "Minimum 2 characters"
}

Special rule "required"

Before explaining all the rules, you need to know the existence of the required rule. This rule is a special rule because you can enable and disable other rules based on if the input is empty or not.

For example, if the surname field is not required and thus may be empty, you can set the required to Boolean false. If the user leaves the input blank, it will not validate the input:

$validator = new Validator();
$valdiator -> field('fieldname') -> required(false) -> lengthmax(20);

Note: the required method should always comes before other rules. Note: an array with zero elements is also validated as an empty input and thus it will not be validated if required is Boolean false

Validation rules

Below is a list of all the validation rules.

Accepted

Check whenever a checkbox is checked or not.

$validator -> field('fieldname') -> accepted();
After

Check whenever a value is after a given date. You need to pass a date format. See "Date format" section for accepted formats.

$validator -> field('fieldname') -> after('2000-01-01', 'Y-m-d');
Alpha

Check whenever a value only contains alpha characters (letters a-z, A-Z).

$validator -> field('fieldname') -> alpha();
Alphadash

Check whenever a value only contains alphadash characters (letters a-z, A-Z, digits 0-9, dashes and underscores).

$validator -> field('fieldname') -> alphadash();
Alphanumeric

Check whenever a value only contains alphanumeric characters (letters a-z, A-Z and digits 0-9).

$validator -> field('fieldname') -> alphanumeric();
Before

Check whenever a value is before a given date. You need to pass a date format. See "Date format" section for accepted formats.

$validator -> field('fieldname') -> before('2020-01-01', 'Y-m-d');
Between

Check whenever a value is between two numbers. Between accepts two parameters. A minimum and a maximum in Float, Int or a string number

$validator -> field('fieldname') -> between(5, 10);
Contains

Check whenever a value contains a specified string.

$validator -> field('fieldname') -> contains('abc');
Different

Check whenever a value is not the same as a value of another field name. See the notequal rule if you want to compare a given value and the notdifferent rule if you want the same values.

$validator -> field('fieldname-one' -> different('fieldname-two');
Email

Check whenever a value is a valid email address.

$validator -> field('fieldname') -> email();
Equals

Check whenever a value is equal to a given string. A second parameter can be given if you want to check in strict mode. Strict mode lets you compare not only the value but also the type of the value. Default is Boolean false.

$validator -> field('fieldname') -> equals('abc', true);
In

Check whenever a value exists in an Array. See the notin rule for the opposite.

$validator -> field('fieldname') -> in(['a', 'b', 'c']);
IP

Check whenever a value is a valid IPV4 or IPV6 address.

$validator -> field('fieldname') -> ip();
IPV4

Check whenever a value is a valid IPV4 address.

$validator -> field('fieldname') -> ipv4();
IPV6

Check whenever a value is a valid IPV6 address.

$validator -> field('fieldname') -> ipv6();
Isdate

Check whenever a value is a valid date. You need to pass a date format. See "Date format" section for accepted formats.

$validator -> field('fieldname') -> isdate('Y-m-d');
Isint

Check whenever a value is a integer number. Isint is not type strict.

$validator -> field('fieldname') -> isint();
Isnumeric

Check whenever a value is a valid number. Isnumeric is not type strict.

$validator -> field('fieldname') -> isnumeric();
Isstring

Check whenever a value is a String.

$validator -> field('fieldname') -> isstring();
JSON

Check whenever a value is a valid JSON string.

$validator -> field('fieldname') -> json();
Length

Check whenever the length of a value is equal to a given length. See also lengthbetween, lengthmax and lengthmin rules.

$validator -> field('fieldname') -> length(10);
Lengthbetween

Check whenever the length of a value is between to given lengths.

$validator -> field('fieldname') -> lengthbetween(5, 10);
Lengthmax

Check whenever the length of a value is equal or less than a given length.

$validator -> field('fieldname') -> lengthmax(10);
Lengthmin

Check whenever the length of a value is equal or greater than a given length.

$validator -> field('fieldname') -> lengthmin(10);
Max

Check whenever a value is equal or less than a given maximum. Good for comparing numbers.

$validator -> field('fieldname') -> max(10);
Maxwords

Check whenever the amount of words is equal or less than a given maximum amount.

$validator -> field('fieldname') -> maxwords(20);
Min

Check whenever a value is equal or greater than a given minimum. Good for comparing numbers.

$validator -> field('fieldname') -> min(5);
Minwords

Check whenever the amount of words is equal or greater than a given minimum amount.

$validator -> field('fieldname') -> minwords(5);
Notcontains

Check whenever a value not contains a specified string. See the contains rule for the opposite.

$validator -> field('fieldname') -> notcontains('abc');
Notdifferent

Check whenever a value is the same as a value of another field name. See the equal rule if you want to compare a given value and the different rule if you don't want the same values.

$validator -> field('fieldname-one' -> notdifferent('fieldname-two');
Notequals

Check whenever a value is not equal to a given string. A second parameter can be given if you want to check in strict mode. Strict mode lets you compare not only the value but also the type of the value. Default is Boolean false.

$validator -> field('fieldname') -> notequals('abc', true);
Notin

Check whenever a value does not exists in an Array. See the in rule for the opposite.

$validator -> field('fieldname') -> in(['a', 'b', 'c']);
Present

Check whenever a value is present. If an input is deleted or not submitted, you can check if it exists with the present rule.

$validator -> field('fieldname') -> present();
Regex

Check whenever a value is valid compared to a given regex. You may give the regex as a String or RegExp object.

$validator -> field('fieldname') -> regex('^[a-z]+$');
URL

Check whenever a value is a valid URL. Set the first and only parameter to check if a URL contains a valid protocol.

$validator -> field('fieldname') -> url();
$validator -> field('fieldname') -> url(true); //Url needs to have a valid protocol like "https://"
Words

Check whenever the amount of words equals a given amount.

$validator -> field('fieldname') -> words(10);

Date formatting

sFire Form Validator has multiple date validation rules that require a date format parameter. These parameters will follow the rules of the date function.

Combining

Sometimes you need to check multiple input values as one value. sFire lets you combine them into a new value for validation using the glue or format method described below.

HTML
<input type="text" name="year" value="2020">
<input type="text" name="month" value="01">
<input type="text" name="day" value="01">

Combining with the glue method

You can combine multiple fields with the glue method:

$validator = new Validator();
$validator -> combine('year', 'month', 'day') -> glue('-') -> name('date');
$validator -> field('date') -> isdate('Y-m-d');

You create a new field name called "date" and execute the validation

Combining with the format method

You can also combine multiple fields with the format method for more control:

$validator = new Validator();
$validator -> combine('year', 'month', 'day') -> format('%s-%s/%s) -> name('date');
$validator -> field('date') -> isdate('Y-m/d');

Each %s is replaced with the specified input field name order.

Custom messages

Each validation rule has its own error message. If you want to set a custom message per rule or even per rule in combination with a field, you may do so.

Custom message per rule

Set custom error message for all fields with the equals rule. You can inject the parameter using the %s characters. To escape this, you can add an extra "%" character.

$validator = new Validator();
validator -> field('amount') -> equals('1000');
validator -> setMessage() -> equals('Only %s as value is accepted'); //Outputs "Only 1000 as value is accepted"

Custom message per rule and per field

Set custom error message for the "amount" field with the equals rule.

$validator = new Validator();
validator -> field('amount') -> equals('1000');
validator -> setMessage('amount') -> equals('Only %s as value is accepted'); //Outputs "Only 1000 as value is accepted"

Custom validator functions

sFire Form Validator has a lot of built-in validation rules. But if you want for example check an e-mail address in a database, you have to build your own validation rule. You may use the extend method to build a custom validation rule or use the load method to load your own validation rule from a validation file.

Extending

The extend function accepts a minimal of three parameters. The first parameter will be the field name. The second parameter is a callable function and the third parameter is the error message when the validation fails.

The callable function (second parameter) will be injected with two parameters. The field name and the value of the input.

$validator = new Validator();
$validator -> extend('fieldname', function($field, $value) {

    if(value !== '10') { 
        return false;
    } else { 
        return true;
    }
}, 'Value not equals 10');

if($validator -> passes()) {
    //Validation success
}

Loading validation file

You can load your own validation files. Check the validation file documentation for more information.