4

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.

2 Answers 2

8

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 >.

Sign up to request clarification or add additional context in comments.

2 Comments

I have given your expression .First time I enter "<html>" ,that shows error message "Invalid entry". that is OK for me. Net I tried "abcd", but it again shows "Invalid entry".I need to allow this normal text.
Sorry, I missed the asterisk.
-1

RegularExpression to avoid any html tags entry use:

[RegularExpression("^[^<>,<|>]+$", ErrorMessage = "Html tags are not allowed.")]

2 Comments

Mind the downvoters comment? The regex part seems correct. If somebody wants to use it to just inform the user, seems fine to me..
This regex doesn't do what it appears to do. It matches any string that contains one or more characters that aren't in the following list: < > , < | > So in addition to preventing angle brackets (twice!) it also prevents commas and pipes, which is potentially a bad idea (users like commas).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.