How to write Regex expression (with C#) to check if there are no characters “<” and “>”?
I wrote code on console for testing:
Regex reg = new Regex(@"^(?!(.*<+.*)|(.*>+.*))");
string[] array = { "any text", "$baks> fgg", "att <br /> dfsdf", "<<script />> sdfsdf", "@##%%^^&&" };
foreach (var str in array)
{
if (reg.IsMatch(str))
Console.WriteLine("OK:\t\t{0}", str);
else
Console.WriteLine("XSS ATTACK:\t{0}", str);
}
Result is:
OK: any text
XSS ATTACK: $baks> fgg
XSS ATTACK: att <br /> dfsdf
XSS ATTACK: <<script />> sdfsdf
OK: @##%%^^&&
But if I use this expression for validating property like
[RegularExpression(@"^(?!(.*<+.*)|(.*>+.*))")]
it fires on any word.
Why? How to write correct expression?
This is just simple validation on client. Full validation realized on server side with AntiXSS.
Thank you.
A client-side RegularExpressionValidator uses Javascript to perform the validation. Javascript-regexes do not understand the “advanced” features, like that
(?! ... ).Try this as the entire expression:
[^<>]*, meaning everything except the<and>.Also note that the RegexValidator acts as if the expression is always ‘anchored’ with
^and$.