Abin Thomas
Abin Thomas

Reputation: 77

What regex expression will only allow one to 3 words?

I am doing a project in Visual Studio Windows Form with C#. I am attempting to validate the data in a textbox to only allow one, two or three words. Right now my code will allow two or more words, but not just one word. It will also not prevent more than 3 words. Can someone help me?

Regex expression = new Regex(@"[A-Za-z]*[ ]{1}[A-Za-z]*[ ]{1}[A-Za-z]*");
if (!expression.Match(DescriptionTxtBox.Text).Success)
{
    MessageBox.Show("The description should be one, two or three words", "Invalid Format for Description", MessageBoxButtons.OK, MessageBoxIcon.Error);
    DescriptionTxtBox.Clear();
    DescriptionTxtBox.Focus();
    return; 
}

Upvotes: 1

Views: 6098

Answers (2)

Anirudha
Anirudha

Reputation: 32797

You can use the following regex

^\s*([a-zA-Z]+\s*){1,3}$

^ depicts start of the string

$ depicts end of the string

{n} is a quantifier that matches exactly n times

{n,} at least n matches

{n,m} between n to m matches

\s represents space and is similar to [\n\r\t\f]


You should use the IsMatch method

Upvotes: 3

RideTheWalrus
RideTheWalrus

Reputation: 84

Have you considered using the String.Split method to separate out your data, and then simply checking that the resulting array is of Length <= 3?

Note that this approach will allow empty strings to pass this test, so you should probably do a check for String.IsNullOrEmpty also.

Upvotes: 0

Related Questions