Using RequiredField Validator with CKEditor in ASP.Net

Last day I have faced a problem with CKEDITOR and asp.net required field validator. Strange problem! When I left blank the textarea(CKEDITOR) required field validate it properly. But when I filled up textarea still now required field validator showed error message for entering data.

After some r&d I have found that the requiredfield validator control will not work properly when it is used with a textarea that is configured with CKEditor. This is due to the fact that, the CKEditor content will not be synched to the page element(textarea) properly when the validator control fire.

To overcome this difficulty, we need to call the method .updateElement() in order to sync or post the content back to the textarea.

Solution:


<head>
<title>CKEDITOR TEST</title>
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>

<script type="text/javascript" language="javascript">

$(document).ready(function() {
var textBoxId = $(".test").attr('id');
if (!CKEDITOR.instances[textBoxId]) {
$('#textBoxId').ckeditor();
});


function UpdateContent() {
var textBoxId = $(".test").attr('id');
if (textBoxId != null) {
var editor = CKEDITOR.instances[textBoxId];
editor.updateElement();
}
}

</script>

</head>

<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" CssClass="test" MaxLength="3000" TextMode="MultiLine" Rows="3" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="No content in CKEditor!"></asp:RequiredFieldValidator>

</div>

<asp:Button ID="btnSave" OnClientClick="javascript:UpdateContent()" runat="server" Text="Save" onclick="btnSave_Click" />

<asp:Label ID="lblError" CssClass="error-msg" runat="server" Text=""></asp:Label>
</form>
</body>

Comments

Sergio said…
Thanks!! It works even without the first part:

$(document).ready(function() {
var textBoxId = $(".test").attr('id');
if (!CKEDITOR.instances[textBoxId]) {
$('#textBoxId').ckeditor();
} //this was missing
});
Anonymous said…
really thanks for it,
it saves time a lot.
Anonymous said…
really thank for it.
it saves time a lot .

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

How can I get a value of a property from an anonymous type (C#)

Check/Uncheck all items in a CheckBoxList using Javascript