Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent html tags entries in mvc textbox using regular expression

I want to prevent any html tags (written between "<>") in a textbox in my mvc 4 application. I have given the data annotation regular expression for my property as follows:

    [RegularExpression(@"&lt;[^>]*>",ErrorMessage="Invalid entry")]
    public string Name { get; set; }

But the regular expression not working correctly. When I type , it shows "Invalid entry".After that, when I type some normal text like "praveen" also shows "Invalid entry" error message.

I have tried another regular expressions something like @"<[^>]*>" ,but same result as above.

Please help.

like image 840
Praveen VR Avatar asked Mar 24 '23 20:03

Praveen VR


1 Answers

You have to logic turned around. The regex you have written is what you do not want to allow, whereas the RegularExpression attribute requires you to enter what you do allow. Anything not matching your regex will show the ErrorMessage.

An alternative regex could be:

@"[^<>]*"

which would disallow < and >.

like image 95
tomsv Avatar answered Apr 25 '23 15:04

tomsv