Reputation: 845
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
Reputation: 5543
Assuming they can be separated by any whitespace character (space, tab, etc):
^[a-z]+(?:\s[a-z]+)+$
Here's the breakdown:
^
[a-z]+
+
(?:\s[a-z]+)+
+
\s
[a-z]+
+
$
...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
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