Reputation: 23
I'm currently using the following regex: ^[^&<>\"'/]*$
and I would like to also add a validation where a user can't just enter a space in the beginning of my textbox. Any ideas pls ? Note: Spaces are allowed but not as the first element
Upvotes: 2
Views: 70
Reputation: 626950
Here is another option: you may allow typing any space (hard or regular one) by adding \p{Zs}
Unicode category class to your regex.
To make sure you still can match an empty string, you need to use a look-ahead anchored at the beginning of the string (that is, you must use it right after ^
start-of-string anchor):
^(?!\p{Zs})[^&<>"'/]*$
//^^^^^^^^^
I strongly suggest using verbatim string literals in C# to declare regexes as you won't have to think about how many backslashes you need to use:
var rx = new Regex(@"^(?!\p{Zs})[^&<>""'/]*$");
Note that you need to double the quotation marks in these literals to declare a single double quote.
var rx = new Regex(@"^(?!\p{Zs})[^&<>""'/]*$");
Console.WriteLine(rx.IsMatch("")); // true - empty string
Console.WriteLine(rx.IsMatch(" sapceAtStart")); // false - space at start
Console.WriteLine(rx.IsMatch(" sapceAtStart")); // false - Hard space at start
Console.WriteLine(rx.IsMatch("space not at start")); // true - space not at start
Upvotes: 0
Reputation: 14350
A negative look-ahead is the way to go here: ^(?! )[^&<>\"'\/]*$
(?! )
means match only if the next character isn't a space. Since that is right after the ^
anchor, that essentially means match only if the first character isn't a space.
Upvotes: 1