简体   繁体   中英

Input field validation constraints using regular expression

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.

您与正则表达式非常接近,只需添加量词并删除\\s

/^[a-zA-Z][a-zA-Z0-9]+$/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM