Depends what approach you want to use and how much you want to customize the validation.
If you decide on the regexp approach, you'd be able to approach it like so:
https://docs.phalcon.io/en/3.2/api/Phalcon_Validation_Validator_Regex
$validator = new \Phalcon\Validation; // or a custom class which extends it with an initialize() that adds validators
$validator->add(
"telephone",
new \Phalcon\Validation\Validator\Regex(
[
"pattern" => "/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/",
"message" => "The Phone number is invalid",
]
)
);
You could also go more the approach, as shown in the documentation example like so:
<?php
use Phalcon\Validation;
use Phalcon\Validation\Validator\Regex;
use Phalcon\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'telephone',
new PresenceOf(
[
'message' => 'The telephone is required',
'cancelOnFail' => true,
]
)
);
$validation->add(
'telephone',
new Regex(
[
'message' => 'The telephone is required',
'pattern' => '/\+44 [0-9]+/',
]
)
);
$validation->add(
'telephone',
new StringLength(
[
'messageMinimum' => 'The telephone is too short',
'min' => 2,
]
)
);
But if you dislike the Phalcon\Validation\Validator\*
validator logic already provided by Phalcon, and need the most control,
the way to customize it fully would be to extend Phalcon\Validation\Validator
and toss in a method public function validate(\Phalcon\Validation $validator, $attribute)
From there, you'd use it like it were Phalcon\Validation\Validator\Email
or Phalcon\Validation\Validator\Regex
etc.
Alternatively, you could also use Phalcon\Validation\Validator\Callback
which is very powerful in that you can do anything you need within the callback function, writing your own custom logic.