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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With