Reputation: 26312
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
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
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
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
Reputation: 368934
Use \S
(which is negation of \s
= non-whitespace character):
@"^\S+$"
If empty string is allowed, replace +
with *
:
@"^\S*$"
Upvotes: 3