0

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.

11
  • Use pattern="/^[a-zA-Z][a-zA-Z0-9]*$/". \s+ matches 1+ whitespaces, why add what you want to forbid? Commented Jun 2, 2016 at 8:39
  • I am new to this but anywaysThank you wiktor :) Commented Jun 2, 2016 at 8:47
  • Do you want to accept 1 letter words? Commented Jun 2, 2016 at 8:48
  • Now I am thinking about it o_O Commented Jun 2, 2016 at 8:49
  • :) Use * at the end to allow 0 or more characters (and 1 letter words), or Toto's + to only allow 2 or more letter words. Commented Jun 2, 2016 at 8:50

2 Answers 2

2

You are very close with your regex, just add quantifier and remove \s:

/^[a-zA-Z][a-zA-Z0-9]+$/
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.