A.T.
A.T.

Reputation: 26312

Negating specific characters in regex

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?

Upvotes: 2

Views: 5617

Answers (4)

Tassisto
Tassisto

Reputation: 10345

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 == ' ';
}

Upvotes: 0

user3458
user3458

Reputation:

^ 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.

Upvotes: 3

cilerler
cilerler

Reputation: 9420

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

Upvotes: 2

falsetru
falsetru

Reputation: 368934

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

@"^\S+$"

If empty string is allowed, replace + with *:

@"^\S*$"

Upvotes: 3

Related Questions