williamsandonz
williamsandonz

Reputation: 16430

Custom validation of CKEditor (RTE) in ASP.NET MVC

I'm using ASP.NET MVC & CKEditor (Basic) to get input (almost exactly like this stack overflow RTE.) User's are limited to bold,italic,links.

I'm assuming I need to validate this server-side, incase someone issues CURL requests to my controller with any desired HTML in it. (I.E so they weren't limited by client-side validation).

So I need to allow, bold, italic, link tags, lists, but absolutely nothing else, how can this be achieved? I'll have a custom validator on my view model, but what is the best way to structure this custom validator? What to look for etc?

Upvotes: 1

Views: 557

Answers (1)

Drewman
Drewman

Reputation: 947

This could be achieved through regex and negative lookahead.

Something like that <(?!br/|br /|a|/a|strong|/strong|b|/b|i|/i|ul|/ul|li|/li>).+?> would match all tags except <br />, <a></a>, <strong></strong>, <b></b>, <i></i>, <ul></ul>, and <li></li>.

Then you could replace the matched occurences with an empty string.

For example this input (tested on regextester.com) :

test <a href="http://www.test.com">test link</a>
Some <strong>text in bold</strong> and <b>another one</b> but also something
in <i>italic</i>
<ul>
    <li>Now</li>
    <li>a list</li>
</ul>
<table>
    <tr>
         <td>And a table</td>
    </tr>
</table>
<br />
<hr />

Would become :

test <a href="http://www.test.com">test link</a>
Some <strong>text in bold</strong> and <b>another one</b> but also something 
in <i>italic</i>
<ul>
    <li>Now</li>
    <li>a list</li>
</ul>

And a table

<br />

Upvotes: 1

Related Questions