Ammar Khan
Ammar Khan

Reputation: 2585

MVC Data Annotation Regex not allow White Space and Commas

I have a property username in my model class on which I want to put a validation to restrict user to enter any white space or comma. Currently it's only restrict white space using the following regex but I want to restrict the comma as well. Please suggest

[Required]
[Display(Name = "UserName")]        
[RegularExpression(@"^\S*$", ErrorMessage = "Username Cannot Have Spaces")]
public string UserName { get; set; }

Upvotes: 3

Views: 6214

Answers (2)

SandRock
SandRock

Reputation: 5573

This one allows anything but comma and whitespace.

^[^\s\,]*$

Upvotes: 2

tchelidze
tchelidze

Reputation: 8308

Try following Regex, it matches white spaces and comma.

^[^\s\,]+$

Upvotes: 7

Related Questions