Reputation: 1096
I am working on a symfony(2.8) project. Where in the registration form needs some input validation. I need to set following constraints on the Subdomain name input field: 1. Should contain only alphanumeric characters 2. First character can not be a number 3. No white spaces
I am using annotations for this task. Here is the Assert statement I am using:
@Assert\Regex(pattern="/^[a-zA-Z][a-zA-Z0-9]\s+$/", message="Subdomain name must start with a letter and can only have alphanumeric characters with no spaces", groups={"registration"})
When I enter any simple string of words eg. svits, it still shows the error message "Subdomain name must start with a letter and can only have alphanumeric characters with no spaces" Any suggestions would be appreciated.
Upvotes: 0
Views: 805
Reputation: 626802
Your pattern does not work because:
The [a-zA-Z0-9]
only matches 1 alphanumeric character. To match 0 or more, add *
quantifier (*zero or more occurrences of the quantified subpattern), or +
(as in Toto's answer) to match one or more occurrences (to only match 2+-letter words).
Since your third requirement forbids the usage of whitespaces in the input string, remove \s+
from your pattern as it requires 1 or more whitespace symbols at the end of the string.
So, my suggestion is
pattern="/^[a-zA-Z][a-zA-Z0-9]*$/"
^
to match 1+ letter words as full strings that start with a letter and may be followed with 0+ any alphanumeric symbols.
To allow whitespaces in any place of the string but the start, put the \s
into the second [...]
(character class):
pattern="/^[a-zA-Z][a-zA-Z0-9\s]*$/"
^^ ^
If you do not want to allow more than 1 whitespace on end (no 2+ consecutive whitespaces), use
pattern="/^[a-zA-Z][a-zA-Z0-9]*(?:\s[a-zA-Z0-9]+)*$/"
^^^^^^^^^^^^^^^^^^^
The (?:\s[a-zA-Z0-9]+)*
will match 0+ sequences of a single whitespace followed with 1+ alphanumerics.
Upvotes: 2
Reputation: 91385
You are very close with your regex, just add quantifier and remove \s
:
/^[a-zA-Z][a-zA-Z0-9]+$/
Upvotes: 2