symfony2 entity validation regexp a-z A-Z 0-9

12,288

Solution 1

You should use the native Regex validator,

It's as simple as using the Regex assert annotation as follow,

use Symfony\Component\Validator\Constraints as Assert;

class YourClass
{
   /**
    * @Assert\Regex("/[a-zA-Z0-9]/")
    */        
    protected $yourProperty;
}

You can also customize your validation by setting the match option to false in order to assert that a given string does not match.

/**
 * @Assert\Regex(
 *     pattern="/[a-zA-Z0-9]/",
 *     match=false,
 *     message="Your property should match ..."
 * )
 */
protected $yourProperty;

Using annotation is not the only way to do that, you can also use YML, XML and PHP, check the documentation, it's full of well explained examples that address this issue.

Solution 2

I couldn't get the previous answer to work correctly. I think it is missing a repeat quantifier (+). Even then, it would match substrings if the offending characters were at the beginning or end of the string, so we need start ^ and end $ restrictions. I also needed to allow dashes and underscores as well as letters and numbers, so my final pattern looks like this.

 * @Assert\Regex("/^[a-zA-Z0-9\-\_]+$/")

I am using Symfony 2.8, so I don't know if the Regex validation changed, but it seems unlikely.

A good resource for testing regex patterns is regex101.com.

Share:
12,288
Matt Welander
Author by

Matt Welander

Updated on June 10, 2022

Comments

  • Matt Welander
    Matt Welander almost 2 years

    Is there a built-in way in symfony2 to validate a string (in my case the username and one other property) against the classic a-z, A-Z and 0-9 rule?

    Would I have to write that in regexp myself as a custom validator? (if so, hint where to look is appreciated)

  • Ryaner
    Ryaner over 7 years
    The restrictions are a good idea. The reason the previous example didn't work is 'match=false' results in the validation passing only if the regex does NOT match.