Snake Eyes
Snake Eyes

Reputation: 16764

How to check if a string contains HTML code in ASP.NET MVC model validation?

I have a model string which looks like:

bla bla bla <b>asdad</b> bla bla bla bla <u>bla</u> ...

My model:

public class MyModel {
      [RegularExpression( @"^(<\s*([^ >]+)[^>]*>.*?<\s*\/\s*\1\s*>)$", ErrorMessage = "No tag is allowed !")]
      public string Text { get; set; }
}

I tried to negate above regex ( I know that I didn't use correctly and I don't know how to do this correctly)

I want to show error when Text contains any match of HTML code, even it has no closed tag, means should occur when met:

<b> without </b>

</b> or similar

How to achieve this with regex ?

Upvotes: 5

Views: 10234

Answers (2)

Quinn
Quinn

Reputation: 4504

The following regex matches if a model string contains no HTML tags:

^((?!\<(|\/)[a-z][a-z0-9]*>).)*$

The demo is HERE

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

This is the regex for that:

<(\s*[(\/?)\w+]*)

It checks for even if single closing tag is there or opening tag is there, it matches that.

DEMO here

Upvotes: 5

Related Questions