2

How can I block white space in textbox entries?

I tried this but it is not working:

  [RegularExpression(@"/^\s/", ErrorMessage = "white space is not allowed in username")]
  public string UserName { get; set; }

'^' negation should not allow white space in text but it does not allow me to enter any text in field. Any help?

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
A.T.
  • 21,626
  • 7
  • 42
  • 63

4 Answers4

2

Use \S (which is negation of \s = non-whitespace character):

@"^\S+$"

If empty string is allowed, replace + with *:

@"^\S*$"
falsetru
  • 336,967
  • 57
  • 673
  • 597
2

Just saw the comment you said "you need to work with DataAnnotation", here is the way to do it without Regex

public class WhiteSpaceCheckerAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var strValue = value as string;
        return strValue != null && !strValue.Contains(" ");
    }
}

usage

[WhiteSpaceChecker(ErrorMessage = "white space is not allowed in username")]
public string UserName { get; set; }

This doesn't cover client side validation which you can easily implement. Following link should help you with that concept Client-side custom data annotation validation

Community
  • 1
  • 1
cilerler
  • 8,439
  • 9
  • 55
  • 85
2

^ works as "negation" only inside character classes, e.g. [^ ] means any character except space. When used outside of [], ^ means "at the beginnign of the string. So your original RE says "A space at the start of the string" - almost exactly the opposite to what you want.

I am not the familiar with specifics of C# REs, but from the rest of the answers, the RE you want is probably ^\S+$: 1 or more non-space characters between beginning and end of the string.

  • i am not familiar with Regex, my requirement is to not allow white space in string, all other characters and symbols are allowed – A.T. Dec 27 '13 at 14:47
  • This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Character Classes". – aliteralmind Apr 10 '14 at 00:16
0

You can do this without RegEx. By adding this code in the KeyPress Event of your textbox.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = e.KeyChar == ' ';
}
Tassisto
  • 9,235
  • 27
  • 93
  • 145