1

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?

dasdom
  • 13,539
  • 2
  • 41
  • 53
A.T.
  • 18,248
  • 7
  • 39
  • 59

4 Answers4

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
  • 7,774
  • 8
  • 51
  • 81
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
1

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

@"^\S+$"

If empty string is allowed, replace + with *:

@"^\S*$"
falsetru
  • 314,667
  • 49
  • 610
  • 551
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
  • 8,589
  • 27
  • 91
  • 140