How to Validate TinyMCE Editor Control with CustomValidator in ASP.NET

No.of Views4200
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  18 Dec 2010 08:12:42
Tag : ASP.NET , Validation Control
In this article I will show to how to validate TinyMCE editor control in ASP.NET. The TinyMCE editor control can validate using RequiredFieldValidator control, but if you are enter only a space, the RequiredFieldValidator control does not validate and its allow to submit.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article I will show to how to validate TinyMCE editor control in ASP.NET. The TinyMCE editor control can validate using RequiredFieldValidator control, but if you are enter only a space, the RequiredFieldValidator control does not validate and its allow to submit.

Implementation

Let’s create a simple page with TinyMCE editor control In ASP.NET using Visual Studio 2008. You can download TinyMCE control package from here.

And also add a RequiredFieldValidator control and set ControlToValidate Property with TinyMCE control. The html code like below,

HTML Code

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to Validate TinyMCE Editor Control using CustomValidator in ASP.NET</title>

    <script type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>

    <script type="text/javascript">
   tinyMCE.init({
        mode : "textareas",
        theme : "simple",
        plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : false,
        height:400
    });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtEditor" runat="server" Width="960px" TextMode="MultiLine"></asp:TextBox>
        <div style="text-align: left; margin-top: 5px; margin-bottom: 5px;">
            <asp:RequiredFieldValidator ControlToValidate="txtEditor" SetFocusOnError="false"
                Display="Dynamic" ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter message body"></asp:RequiredFieldValidator></div>
        <div style="text-align: center; margin-top: 5px;">
            <asp:Button ID="btnSave" runat="server" Text="Save" /></div>
    </div>
    </form>
</body>
</html>

Note: I have use the simple version TinyMCE editor control for this demonstration.

The Page looks like below,

Image Loading

Now run application and click save button, the validation control working fine. I have not entered any characters in Editor Control. Below validation message looks like,

Image Loading

Now enter the space and click save button, the message looks like below,

"A potentially dangerous Request.Form value was detected from the client (txtEditor="<p>&nbsp;</p>")."

 The error page looks like below, 

Image Loading

Note: To prevent this error for other case, you have to set ValidationRequest is False in page level, you can see in following html code.
So if I use RequriedFieldValidator Control, the following cases not validating,

  • If user entered space

So now I make a decision RequiredFieldValidator no more working on this case. Let’s I change to use the custom JavaScript function with CustomValidator Control to prevent this error and make sure validation working properly.

The updated Html code looks like below,

HTML Code

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" ValidateRequest="false" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to Validate TinyMCE Editor Control using CustomValidator in ASP.NET</title>

    <script type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>

    <script type="text/javascript">
        tinyMCE.init({
            mode: "textareas",
            theme: "simple",
            plugins: "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: false,
            height: 400
        });
    </script>

    <script language="javascript" type="text/javascript">
        function IsValidContent(sender, args) {
            var isValid = false;
            var value = tinyMCE.get('<%=txtEditor.ClientID%>').getContent();
            if (value == "") {
                args.IsValid = false;
            }
            else {
                // check if user has enter only space with control "<p>&nbsp;</p>"
                var space = "<p>&nbsp;</p>";
                if (value ==space) {
                    // run command to clear space with TinyMce command
                    tinyMCE.get('<%=txtEditor.ClientID%>').execCommand('mceSetContent', false, "");
                    args.IsValid = false;
                }
                else {
                    args.IsValid = true;
                }
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtEditor" runat="server" Width="960px" TextMode="MultiLine"></asp:TextBox>
        <div style="text-align: left; margin-top: 5px; margin-bottom: 5px;">
            <asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="IsValidContent"
                runat="server" ErrorMessage="Please enter message body"></asp:CustomValidator></div>
        <div style="text-align: center; margin-top: 5px;">
            <asp:Button ID="btnSave" runat="server" Text="Save" /></div>
    </div>
    </form>
</body>
</html>

In the new html code, I have added CustomValidator Control instead of RequriredFieldValidator and also composed new JavaScript function to get control  body and check in first validation if is the length is less than or equal to 0, then custom function return false. And also if users enter space then I have to remove space using TinyMCE Command. And then have to validate in second condition and return false otherwise return true. The Complete script will be like below,

Javascript

<script language="javascript" type="text/javascript">
        function IsValidContent(sender, args) {
            var isValid = false;
            var value = tinyMCE.get('<%=txtEditor.ClientID%>').getContent();
            if (value == "") {
                args.IsValid = false;
            }
            else {
                // check if user has enter only space with control "<p>&nbsp;</p>"
                var space = "<p>&nbsp;</p>";
                if (value ==space) {
                    // run command to clear space with TinyMce command
                    tinyMCE.get('<%=txtEditor.ClientID%>').execCommand('mceSetContent', false, "");
                    args.IsValid = false;
                }
                else {
                    args.IsValid = true;
                }
            }
        }
    </script>

Let’s run the application try again same test cases, the result will be like below,

 

Image Loading

References

Download Sample Project

Download source files -646 kb

Conclusion

In this you have learned how to validate TinyMCE editor control in ASP.NET. The TinyMCE editor control can validate using RequiredFieldValidator control, but if you are enter only space, the RequiredFieldValidator control does NOT validate and its allow to submit .but in CodeGain we are using FCKEditor than TinyMCE editor post article and resources. Hopes help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top