beginerdeveloper
beginerdeveloper

Reputation: 845

regular expression validate textbox at least two words is required

i have a text box and i need validate it with regular expression at least two words in text box, and not contain spaces in the first character. pls give me a regular expression to validate my textbox

Currently I am using

^((\b[a-zA-Z]{2,40}\b)\s*){2,}$

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
    controltovalidate="TextBox1" validationexpression="^((\b[a-zA-Z]{2,40}\b)\s*){2,}$" 
    errormessage="at least two words"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" OnClick="btnClick" runat="server" Text="Button" />

Upvotes: 2

Views: 6774

Answers (2)

Grinn
Grinn

Reputation: 5543

Assuming they can be separated by any whitespace character (space, tab, etc):

^[a-z]+(?:\s[a-z]+)+$

Here's the breakdown:

  • Assert position at the beginning of the string ^
  • Match a single character in the range between “a” and “z” [a-z]+
    • Between one and unlimited times, as many times as possible +
  • Match the regular expression below (?:\s[a-z]+)+
    • Between one and unlimited times, as many times as possible +
    • Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) \s
    • Match a single character in the range between “a” and “z” [a-z]+
      • Between one and unlimited times, as many times as possible +
  • Assert position at the end of the string (or before the line break at the end of the string, if any) $

...But if they're separated by only a space:

^[a-z]+(?: [a-z]+)+$

...or if any non-word character for the separator:

^[a-z]+(?:\W[a-z]+)+$

This should be used with RegexOptions.IgnoreCase. For example (in C#):

if (Regex.IsMatch(subjectString, @"^[a-z]+(?:\W[a-z]+)+$", RegexOptions.IgnoreCase)) {
    // Successful match
} else {
    // Match attempt failed
} 

Upvotes: 4

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89565

Your are probably looking for this:

^[a-zA-Z]{2,40}(?: +[a-zA-Z]{2,40})+$

Description:

^                       # anchor for the start of the string
[a-zA-Z]{2,40}          # ascii letters
(?:                     # open a non-capturing group
    [ ]+[a-zA-Z]{2,40}  # one or more spaces followed by letters
)+                      # repeat the group one or more times
$                       # anchor for the end of the string

Note that word boundaries are useless.

Upvotes: 1

Related Questions