Custom validators

Validators are simple functions that check if a value matches an expectation.
They can be used to validate entered content in the Panel or to validate the fields of contact or other forms.

Kirby includes many useful validators by default, but sometimes you need a custom one.
In this tutorial you will learn how to do this.

Define your own validator

The best place to define custom validators is in a plugin file.
For example: /site/plugins/validators.php

We will create a validator that validates a value against a custom invoice number format:


// validate against an invoice number of format 2016-ABCD01
v::$validators['invoiceNum'] = function($value) {
  // always make sure to return a boolean value (true or false) from your validator
  // v::match() is also a validator and you can be sure that it does this
  return v::match($value, '/[0-9]{4}-[A-Z]{4}[0-9]{2}/');

As you can see we used another validator inside our validator, the match validator. But you aren't limited to using existing validators, you can use any function that is defined in PHP, Kirby or your plugins.
Just make sure that you always return either true or false.

Our invoice number validator can now be used like this:

v::invoiceNum('Some invalid text'); // false
v::invoiceNum('2015-TEST05');       // true

You can also use the validator inside a blueprint:

    label: Invoice number
    type: text
    validate: invoiceNum

Validators with parameters

One parameter

Our invoice number validator uses a fixed format every time and doesn't need parameters.
But what if you wanted to validate if a number was divisible by another number?

That's no problem either since your validators can have any number of arguments:


// validate if a number is divisible by another number
v::$validators['divisible'] = function($value, $by) {
  return $value % $by === 0;

You only need to make sure that the value to validate is always the first argument.

This validator can now be used like this:

v::divisible(7, 2);  // false
v::divisible(10, 2); // true

Of course that works just as well in a blueprint:

    label: Number of tickets
    type: number
    help: Tickets can only be sold in packs of 5 for technical reasons
      divisible: 5

Multiple parameters

Validators with multiple parameters work just like those with one parameter.
If you want to use them in blueprints, the syntax looks like this:

    label: Example field
    type: text
        - 5
        - 20

(between is already included with Kirby)