Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 301
Matt Welander Avatar asked Oct 31 '13 08:10

Matt Welander


2 Answers

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.

like image 90
Ahmed Siouani Avatar answered Oct 29 '22 05:10

Ahmed Siouani


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.

like image 33
craigh Avatar answered Oct 29 '22 05:10

craigh