This is a migrated thread and some comments may be shown as answers.

How to use RequiredFieldValidator to SetFocusOnError with RadEditor

11 Answers 339 Views
Editor
This is a migrated thread and some comments may be shown as answers.
VnDevil
Top achievements
Rank 2
VnDevil asked on 26 Nov 2010, 06:33 PM
Hi Telerik,

I use a RequiredFieldValidator to check content RadEditor, when error I want to set focus on RadEditor, how can I do??
I use this code below but it doesn't work, please help me

<html>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:Label ID="lblTest" runat="server" />
        <br />
        <br />
        <telerik:RadEditor ID="RadEditor1" runat="server" />
        <asp:RequiredFieldValidator ID="rfvEditor1" runat="server" SetFocusOnError="true" ErrorMessage="*" ControlToValidate="RadEditor1" />
        <asp:Button ID="btnTest" runat="server" Text="OK" />
    </div>
    </form>
</body>
</html>

11 Answers, 1 is accepted

Sort by
0
VnDevil
Top achievements
Rank 2
answered on 30 Nov 2010, 05:07 AM
Anybody help me ?
0
Rumen
Telerik team
answered on 01 Dec 2010, 10:37 AM
Hi,

Here is an example how to implement the desired focus functionality:
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script type="text/javascript">
        Telerik.Web.UI.RadEditor.prototype._registerClientValidation = function () {
            if (typeof (Page_ClientValidate) == "function") {
                var radEditorClientValidate = Page_ClientValidate;
                Page_ClientValidate = Function.createDelegate(this, function (validationGroup) {
                    //memory leak?
                    var editorElement = this.get_element();
                    if (editorElement) {
                        var newContent = this._updateHiddenTextarea();
                        editorElement.value = newContent;
                        editorElement.setAttribute("value", newContent);
                    }
                    editorElement = null;
                    var isValid = radEditorClientValidate(validationGroup);
                    if (!isValid)
                        this.setFocus();
                    return isValid;
                });
            }
        }
    </script>
    <div>
        <asp:Label ID="lblTest" runat="server" />
        <br />
        <br />
        <telerik:RadEditor ID="RadEditor1" runat="server" />
        <asp:RequiredFieldValidator ID="rfvEditor1" runat="server" SetFocusOnError="true"
            ErrorMessage="*" ControlToValidate="RadEditor1" />
        <asp:Button ID="btnTest" runat="server" Text="OK" />
    </div>
    </form>
</body>
</html>


Kind regards,
Rumen
the Telerik team
Browse the vast support resources we have to jumpstart your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Steele
Top achievements
Rank 1
answered on 20 Jan 2011, 07:15 AM
Is this the official way to get validators working with the RadEditor?
The memory leak comment in the code makes me think that this is not ready for production.
Can you elaborate more on what approach to use here?
Thanks,
Steele.
0
Rumen
Telerik team
answered on 21 Jan 2011, 05:56 PM
Hi Steele,

You should don't worry about the comment about the memory leak. The source is taken from the official source code of RadEditor, which is extensively tested for memory leaks. If you experience any memory leaks with our control, please provide an example and our developers will fix them.

All the best,
Rumen
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Steele
Top achievements
Rank 1
answered on 24 Jan 2011, 06:35 AM
Hi Rumen,
No memory leaks found, but no success getting this working in a radgrid.
I am using a radeditor in a radgrids EditItemTemplate.  Can you give me an example of an aspx which shows this functionality?
What I have so far is :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridButtonIndex.aspx.cs" Inherits="TestTelerikWebApp.GridButtonIndex" %>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
</head>
<body onload="FixEditor();">
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            function OnGridCommand(sender, args) {
                var grid = sender;
                debugger;
                if (args.get_commandName() == "InitInsert" && grid._editIndexes[0] >= 0) {
                    alert("Cannot add while editing a record.");
                    args.set_cancel(true);
                }
                if (args.get_commandName() == "Delete") {
                    if (grid._editIndexes[0] >= 0) {
                        alert("Cannot delete while editing a record.");
                        args.set_cancel(true);
                    }
                    else
                        var value = confirm("Are you sure you want to delete?");
                    if (!value)
                        args.set_cancel(true);
                }
            }
  
            function FixEditor() {
                if (typeof (Telerik.Web.UI.RadEditor) != "undefined") {
                    Telerik.Web.UI.RadEditor.prototype._registerClientValidation = function () {
                        if (typeof (Page_ClientValidate) == "function") {
                            alert('1');
                            var radEditorClientValidate = Page_ClientValidate;
                            Page_ClientValidate = Function.createDelegate(this, function (validationGroup) {
                                var editorElement = this.get_element();
                                if (editorElement) {
                                    var newContent = this._updateHiddenTextarea();
                                    editorElement.value = newContent;
                                    editorElement.setAttribute("value", newContent);
                                }
                                editorElement = null;
                                var isValid = radEditorClientValidate(validationGroup);
                                if (!isValid) {
                                    alert('focussing');
                                    this.setFocus();
                                }
                                return isValid;
                            });
                        }
                    }
                }
            }
              
        </script>
    </telerik:RadCodeBlock>
    <script type="text/javascript">
          
    </script>
    <div>
        <telerik:RadGrid ID="dgTest" runat="server" AutoGenerateColumns="False" GridLines="None"
            OnItemCommand="dgTest_ItemCommand" OnNeedDataSource="dgTest_NeedDataSource" 
            onprerender="dgTest_PreRender">
            <ClientSettings>
                <ClientEvents OnCommand="OnGridCommand" />
            </ClientSettings>
            <MasterTableView CommandItemDisplay="Top">
                <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
                <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                    <HeaderStyle Width="20px"></HeaderStyle>
                </RowIndicatorColumn>
                <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                    <HeaderStyle Width="20px"></HeaderStyle>
                </ExpandCollapseColumn>
                <Columns>
                    <telerik:GridTemplateColumn DataField="Description" HeaderText="Description" UniqueName="Description"
                        ConvertEmptyStringToNull="False">
                        <HeaderStyle Width="30%" />
                        <EditItemTemplate>
                            <table>
                                <tr valign="top">
                                    <td>
                                        <telerik:RadEditor ID="reDescription" runat="server" EditModes="Design" Content="<%# Bind('Description') %>"
                                            Height="200px">
                                        </telerik:RadEditor>
                                        <script type="text/javascript">
                                              
                                              
                                        </script>
                                    </td>
                                    <td style="width: 20px" align="right">
                                        <span style="color: Red">*</span><asp:RequiredFieldValidator ID="rfvDesc" runat="server"
                                            ControlToValidate="reDescription" Display="Dynamic" ErrorMessage="This is a required field"
                                            ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
                                    </td>
                                </tr>
                            </table>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblDescEval" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
                    <telerik:GridButtonColumn ButtonType="PushButton" CommandName="TestClick" FilterControlAltText="Filter colButt column"
                        Text="Press Me" UniqueName="colButt">
                    </telerik:GridButtonColumn>
                </Columns>
                <EditFormSettings>
                    <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                    </EditColumn>
                </EditFormSettings>
            </MasterTableView>
            <FilterMenu EnableImageSprites="False">
            </FilterMenu>
            <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
            </HeaderContextMenu>
        </telerik:RadGrid>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="dgTest">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="dgTest" />
                        <telerik:AjaxUpdatedControl ControlID="lblFeedback" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
    </div>
    <asp:Label ID="lblFeedback" runat="server"></asp:Label>
      
    </form>
</body>
</html>

And code behind :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
  
using System.Data;
using Telerik.Web.UI;
using System.Collections;
  
namespace TestTelerikWebApp
{
    public partial class GridButtonIndex : System.Web.UI.Page
    {
        protected DataTable GetData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("Description", typeof(string));
            DataRow dr = dt.NewRow();
            dr["Id"] = 1;
            dr["Description"] = "Test 1";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["Id"] = 2;
            dr["Description"] = "Test 2";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["Id"] = 3;
            dr["Description"] = "Test 3";
            dt.Rows.Add(dr);
  
            return dt;
        }
  
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                  
            }
        }
  
        protected void dgTest_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            RadGrid rg = (RadGrid)sender;
            rg.DataSource = GetData();
        }
  
        protected void dgTest_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "TestClick")
            {
                GridEditableItem gei = (GridEditableItem)(e.Item);
                lblFeedback.Text = "Item Index is : " + gei.ItemIndex.ToString();
                lblFeedback.Text += "<br/>Item CommandArgument is : " + e.CommandArgument.ToString();
            }
        }
  
        protected void dgTest_PreRender(object sender, EventArgs e)
        {
            RadGrid TheGrid = (RadGrid)sender;
            if (TheGrid.EditItems.Count > 0 || TheGrid.MasterTableView.IsItemInserted)
            {
                //RadAjaxManager1.ResponseScripts.Add("FixEditor();");
            }
        }
    }
}

Thanks for your help.
Steele.
0
Rumen
Telerik team
answered on 26 Jan 2011, 05:09 PM
Hi VnDevil,

Please, find attached an example demonstrating how to set the focus in RadEditor when the validator fires.

Best regards,
Rumen
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Steele
Top achievements
Rank 1
answered on 27 Jan 2011, 12:34 AM
Thanks for the example Rumen.  But I have a couple questions/comments about the solution.
  1. This is overriding the object-level definition (prototype) and using an instance-level variable (in the $find). I take it that this will not work if I have more than 1 RadEditor. Is that true?
  2. The javascript used is in fact a replication of the validation rule. So using a validator is really of little use.  Is there a way to test via the validator instead of using the this.get_text() == "" part?

Thanks for the help,
Steele.

0
Steele
Top achievements
Rank 1
answered on 27 Jan 2011, 06:22 AM
For those in the same boat as I have been, please see below a generalised fix for getting the radEditor to take focus on client validation failure.
I call ReassignClientValidate from my OnCommand client event for the grid.  The new function will be assigned the first time client validation has been initialised. 
I hope this will be address in an up-coming release.
Rumen - any comments on my proposed solution? Any shortcomings you can see?
Note : I have not tested it with multiple Validation Groups on the page. Let me know if this helps you out or modifications you find necessary.

// Since the RadEditor is a bit special when it comes to validation (won't take focus on validation failure)
// we need to rejigger the page validation objects to use setFocus()
var gClientValidateOverridden = false;
function ReassignClientValidate() {
    if (gClientValidateOverridden == false) {
        if (typeof (Page_ClientValidate) == 'function') {
            var oldOne = Page_ClientValidate;
            Page_ClientValidate = Function.createDelegate(this, function () {
                var isPageValid = oldOne();
                if (!isPageValid) {
                    debugger;
                    for (var i = Page_Validators.length - 1; i >= 0; i--) {
                        if (!Page_Validators[i].isvalid) {
                            if ($find(Page_Validators[i].controltovalidate) != null) {
                                if (typeof ($find(Page_Validators[i].controltovalidate).setFocus) == "function") {
                                    $find(Page_Validators[i].controltovalidate).setFocus();
                                } else if (typeof ($find(Page_Validators[i].controltovalidate).focus) == "function") {
                                    $find(Page_Validators[i].controltovalidate).focus();
                                }
                            }
                        }
                    }
  
                }
            });
            gClientValidateOverridden = true;
        }
    }
}

Thanks,
Steele.
0
Rumen
Telerik team
answered on 01 Feb 2011, 01:33 PM
Hi guys,

The Insert button of the EditItemTemplate Form postbacks and the validation of the RequiredFieldValidator occurs after the postback, but not before the form submission. This is a standard RadGrid behavior and if you want to prevent it you should implement your own custom Form Template Edit Form as shown in this demo: Form Template Edit Form.

If you have any additional questions, please open a support ticket for the RadGrid control.

Best regards,
Rumen
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Steele
Top achievements
Rank 1
answered on 01 Feb 2011, 11:56 PM
Ok, I have had a similar answer to this quite a few times, and to be honest am finding it somewhat frustrating.
My needs that I outlined in this post were quite clear. I provided an example with indicators as to the issue.
What I got in return was a, well, best described as a hack, that was clearly not suitable for a production site.
After spending more time in trying to find an actual solution and developing my own, I get a reply saying that "yes, this is standard in..." and if "that's what you wanted, you need to..".
That IS what I needed to do. A week prior to my finding my own solution.
To me, what is described here is a bug. I use only Telerik standard features, and controls. I have followed examples, read help files - and none of this indicated that I was using the controls in an unsupported way - Rumen, not even you saw that shown by your project example you attached.
I pay for support, but this experience is giving me doubts over the technical abilities of the client-facing support staff.
I would appreciate contact from Telerik in this regard.
Steele.
0
Daniel
Telerik team
answered on 07 Feb 2011, 03:29 PM
Hello Steele,

I noticed that you use the OnCommand event with server-side binding. Please note that this event is designed to work with client-side binding and may cause problems when used in some server-side binding scenarios like yours.
I recommend that you remove the OnCommand handler and move this code to code-behind:

<ClientSettings>
      <ClientEvents  />
</ClientSettings>

protected void dgTest_ItemCommand(object sender, GridCommandEventArgs e)
{
        //...
}

Let me know whether this helps.

Best regards,
Daniel
the Telerik team
Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
Tags
Editor
Asked by
VnDevil
Top achievements
Rank 2
Answers by
VnDevil
Top achievements
Rank 2
Rumen
Telerik team
Steele
Top achievements
Rank 1
Daniel
Telerik team
Share this question
or