In this article I’ll be explaining how to validate TinyMCE Rich Text Editor or Rich TextBox. If you like to know more about adding TinyMCE editor in ASP.Net application, refer my following article
Directly if you try to add a normal Required Field validator it will simply validate the multiline textbox and not the TinyMCE Editor and gives you Required message. This is because TinyMCE adds its content to the multiline textbox or TextArea after the button is clicked. Hence the required field validators fail to validate it first time and throw validation failed error.
Due to this we might need to press the button twice to make the Form Post happen.
I’ll be explaining two technique to tackle the issue.
Technique 1
In Technique 1, we will force the TinyMCE to save to the content to TextArea or Multiline Textbox so that Required Field validators can validate it properly.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTinyMCE" runat="server" TextMode = "MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate = "txtTinyMCE" runat="server"ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick = "tinyMCE.triggerSave(false,true);" />
</div>
</form>
You just need to add OnClientClick event and call the TinyMCE method that will save the content to the TextArea. Thus validators will now find the content in TextArea and the PostBack will work.
Technique 2
Technique 2 makes use of a Custom Validator instead of a Required Field validator.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTinyMCE" runat="server" TextMode = "MultiLine"></asp:extBox>
<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction = "ValidateTinyMCE" runat="server"ErrorMessage="Required"></asp:CustomValidator>
<asp:Button ID="btnSave" runat="server" Text="Save" />
</div>
</form>
The custom validator calls a JavaScript method (described below) which will validate the TinyMCE Editor and not the TextArea or multiline textbox
<script type = "text/javascript">
function ValidateTinyMCE(sender, args) {
var isValid = false;
var value = tinyMCE.get('<%=txtTinyMCE.ClientID%>').getContent();
if (value == "") {
args.IsValid = false;
}
else {
//Check for space tag
if (value == "<p> </p>") {
//Clear TinyMCE
tinyMCE.get('<%=txtTinyMCE.ClientID%>').execCommand('mceSetContent', false, "");
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
</script>
You just need to place the script in the BODY, HEAD OR ContentPlaceHolder section.
You can download the sample source code using the download link below.
TinyMCE_ASP.Net - Validation.zipref:http://www.aspsnippets.com/Articles/Performing-Validation-in-TinyMCE-Editor-using-ASP.Net-Validation-Controls.aspx
No comments:
Post a Comment