I'm learning regular expression, so please go easy with me!
Username is considered valid when does not start with _
(underscore) and if contains only word characters (letters, digits and underscore itself):
namespace Gremo\ExtraValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class UsernameValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
// Violation if username starts with underscore
if (preg_match('/^_', $value, $matches)) {
$this->context->addViolation($constraint->message);
return;
}
// Violation if username does not contain all word characters
if (!preg_match('/^\w+$/', $value, $matches)) {
$this->context->addViolation($constraint->message);
}
}
}
In order to merge them in one regular expression, i've tried the following:
^_+[^\w]+$
To be read as: add a violation if starts with an underscore (eventually more than one) and if at least one character following is not allowed (not a letter, digit or underscore). Does not work with "_test", for example.
Can you help me to understand where I'm wrong?
You can add a negative lookahead assertion to your 2nd regex:
^(?!_)\w+$
Which now means, try to match the entire string and not any part of it. The string must not begin with an underscore and can have one or more of word characters.