Add validation pattern to form element

We want to validate phone numbers and postal codes.

These validations are based on regexes.

What is the best way to add these validation patterns as the pattern-Attribute to the form field?

Hey Mimmi,

the best way would be implementing it into your form class, where you add your input fields.



namespace Marcel\Form;

use Laminas\Form\Element\Tel;
use Laminas\Form\Form;

class MyForm extends Form
    public function init()

            'type' => Tel::class,
            'name' => 'my-phonenumber',
            'attributes' => [
                 'pattern' => 'your-regex-here',

Additionally, if you want to override the standard RegexValidator implemented in the Tel element class, you can add your own RegexValidator at the input filter implementation for your form. With that change you can use the same regex as you use for the HTML5 constraint validation api.

See also: