3

I am wanting to validate user input on a text box by only allowing (white space, letter, or digit, '-' and '_'). I was wondering if someone could help me with that regexp? I found this SO question, but i am trying it and it is not working.

Here is what i am using:

if (!System.Text.RegularExpressions.Regex.IsMatch(NameTextBox.Text, "/^([a-zA-Z])([a-zA-Z0-9_ -])$/"))

Thanks.

EDIT - New approach.

I actually decided to go with this instead of regex, any reason why i should not?

if (!NameTextBox.Text.All(c=>Char.IsLetterOrDigit(c) || c==' ' || c=='_' || c=='-'))

Reference for the above code.

Community
  • 1
  • 1
prolink007
  • 33,872
  • 24
  • 117
  • 185
  • 1
    Regex in .NET doesn't require the opening and closing /. You might also need to escape the final '-' in the character match for the remaining 80 characters (note that this allows a string up to 81 character currently and also requires at least 2 characters) – Dan Bryant Aug 12 '11 at 18:45
  • why the first [a-zA-Z] group? – Serge Wautier Aug 12 '11 at 18:46
  • 1
    @Serge, OP copied the exact expression from the SO Question http://stackoverflow.com/questions/3469393/how-to-check-input-is-only-a-number-letter-and-space. – Doug Chamberlain Aug 12 '11 at 18:48
  • I decided to go with a different approach after some research. Let me know if there is any reason why i should not do my new attempt. Thanks for all your help everyone. – prolink007 Aug 12 '11 at 18:51
  • 1
    @prolink007 Your other approach is not equivalent. I does not limit the input to between 1 and 80 characters. – rsbarro Aug 12 '11 at 18:55
  • @rsbarro, that was not a requirement, i messed up when i copied the regexp from the other link. I will fix that now. – prolink007 Aug 12 '11 at 18:56

3 Answers3

1

Get rid of the forward slash at the start and end, that's a javascript thing.

"^([a-zA-Z])([a-zA-Z0-9_ -]){1,80}$"

Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91
1

I think this is what you want for your regex: @"^[\w\s-]{1,80}$"

^       match start of string
\w      will match any [A-Za-z0-9_]
\s      will match any whitespace
-       will match the - character
{1,80}  requires between 1 and 80 characters
$       match end of string

If by whitespace, you mean you want to match just space (and not tab let's say), switch it to:

@"^[\w -]{1,80}$"

rsbarro
  • 27,021
  • 9
  • 71
  • 75
1

Try:

([a-zA-Z0-9-_\s])

That group matches lower and upper case a-z, 0-9, "-", "_", and whitespace ("\s").

davecoulter
  • 1,806
  • 13
  • 15