Akshay Chawla
Akshay Chawla

Reputation: 613

How to restrict trailing whitespace in model mvc

I have an registration form which has First name and last name as one of the model property. I dont want the user to enter white spaces at start and end of the string. I want to achieve this using Regex. I tried following code,but this doesn't allow user to enter white space between two words, which i doesn't want to restrict.

[RegularExpression(@"^[^\s]+$", ErrorMessage = "Required.")]

Valid: "John Paul"

Invalid: " John Paul"

Invalid: "John Paul "

Thanks in advance.

Upvotes: 1

Views: 1505

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

To allow one or two words, use

@"^\S+(?:\s+\S+)?$"

where (?:\s+\S+)? matches an optional 1+ non-whitespace symbol sequence (\S+) after 1+ whitespace symbols (\s+).

To allow 1 or more "words", use

@"^\S+(?:\s+\S+)*$"

NOTE: To only allow 1 whitespace between the words, replace \s+ with \s.

NOTE2: If you want to only allow regular spaces (i.e. no tabs, etc.) replace \s with a space.

Details:

  • ^ - start of string
  • \S+ - 1 or more non-whitespace chars
  • (?:\s+\S+)* - a non-capturing group matching 0+ (due to * quantifier) sequences of:
    • \s+ - 1+ (due to + quantifier, remove it if you need to only allow single whitespace between words) whitespaces
    • \S+ - 1 or more non-whitespace chars
  • $ - end of string.

Upvotes: 1

Related Questions