Matt Welander
Matt Welander

Reputation: 8548

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)

Upvotes: 5

Views: 13236

Answers (2)

craigh
craigh

Reputation: 2291

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.

Upvotes: 3

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

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.

Upvotes: 10

Related Questions