Tuesday, February 7, 2012

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>

3 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 .

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...