Regex

Regex

Validates that a value matches a regular expression.

Applies toproperty or method
Options
ClassSymfony\Component\Validator\Constraints\Regex
ValidatorSymfony\Component\Validator\Constraints\RegexValidator

Basic Usage

Suppose you have a description field and you want to verify that it begins with a valid word character. The regular expression to test for this would be /^\w+/, indicating that you’re looking for at least one or more word characters at the beginning of your string:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\Regex("/^\w+/")
    8. */
    9. protected $description;
    10. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. description:
    5. - Regex: '/^\w+/'
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Author">
    7. <property name="description">
    8. <constraint name="Regex">
    9. <option name="pattern">/^\w+/</option>
    10. </constraint>
    11. </property>
    12. </class>
    13. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('description', new Assert\Regex([
    10. 'pattern' => '/^\w+/',
    11. ]));
    12. }
    13. }

Alternatively, you can set the match option to false in order to assert that a given string does not match. In the following example, you’ll assert that the firstName field does not contain any numbers and give it a custom message:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\Regex(
    8. * pattern="/\d/",
    9. * match=false,
    10. * message="Your name cannot contain a number"
    11. * )
    12. */
    13. protected $firstName;
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. firstName:
    5. - Regex:
    6. pattern: '/\d/'
    7. match: false
    8. message: Your name cannot contain a number
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Author">
    7. <property name="firstName">
    8. <constraint name="Regex">
    9. <option name="pattern">/\d/</option>
    10. <option name="match">false</option>
    11. <option name="message">Your name cannot contain a number</option>
    12. </constraint>
    13. </property>
    14. </class>
    15. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('firstName', new Assert\Regex([
    10. 'pattern' => '/\d/',
    11. 'match' => false,
    12. 'message' => 'Your name cannot contain a number',
    13. ]));
    14. }
    15. }

Note

As with most of the other constraints, null and empty strings are considered valid values. This is to allow them to be optional values. If the value is mandatory, a common solution is to combine this constraint with NotBlank.

Options

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

htmlPattern

type: string|boolean default: null

This option specifies the pattern to use in the HTML5 pattern attribute. You usually don’t need to specify this option because by default, the constraint will convert the pattern given in the pattern option into an HTML5 compatible pattern. Notably, the delimiters are removed and the anchors are implicit (e.g. /^[a-z]+$/ becomes [a-z]+, and /[a-z]+/ becomes .*[a-z]+.*).

However, there are some other incompatibilities between both patterns which cannot be fixed by the constraint. For instance, the HTML5 pattern attribute does not support flags. If you have a pattern like /^[a-z]+$/i, you need to specify the HTML5 compatible pattern in the htmlPattern option:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\Regex(
    8. * pattern = "/^[a-z]+$/i",
    9. * htmlPattern = "[a-zA-Z]+"
    10. * )
    11. */
    12. protected $name;
    13. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. name:
    5. - Regex:
    6. pattern: '/^[a-z]+$/i'
    7. htmlPattern: '[a-zA-Z]+'
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Author">
    7. <property name="name">
    8. <constraint name="Regex">
    9. <option name="pattern">/^[a-z]+$/i</option>
    10. <option name="htmlPattern">[a-zA-Z]+</option>
    11. </constraint>
    12. </property>
    13. </class>
    14. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('name', new Assert\Regex([
    10. 'pattern' => '/^[a-z]+$/i',
    11. 'htmlPattern' => '[a-zA-Z]+',
    12. ]));
    13. }
    14. }

Setting htmlPattern to false will disable client side validation.

match

type: boolean default: true

If true (or not set), this validator will pass if the given string matches the given pattern regular expression. However, when this option is set to false, the opposite will occur: validation will pass only if the given string does not match the pattern regular expression.

message

type: string default: This value is not valid.

This is the message that will be shown if this validator fails.

You can use the following parameters in this message:

ParameterDescription
{{ value }}The current (invalid) value

pattern

type: string [default option]

This required option is the regular expression pattern that the input will be matched against. By default, this validator will fail if the input string does not match this regular expression (via the [preg_match](https://www.php.net/manual/en/function.preg-match.php "preg_match") PHP function). However, if match is set to false, then validation will fail if the input string does match this pattern.

normalizer

type: a PHP callable default: null

This option allows to define the PHP callable applied to the given value before checking if it is valid.

For example, you may want to pass the 'trim' string to apply the [trim](https://www.php.net/manual/en/function.trim.php "trim") PHP function in order to ignore leading and trailing whitespace during validation.

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.