How to use RequiredFieldValidator to SetFocusOnError with RadEditor

12 posts, 0 answers
  1. VnDevil
    VnDevil avatar
    58 posts
    Member since:
    Oct 2012

    Posted 26 Nov 2010 Link to this post

    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>
  2. VnDevil
    VnDevil avatar
    58 posts
    Member since:
    Oct 2012

    Posted 29 Nov 2010 Link to this post

    Anybody help me ?
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Rumen
    Admin
    Rumen avatar
    12846 posts

    Posted 01 Dec 2010 Link to this post

    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.
  5. Steele
    Steele avatar
    96 posts
    Member since:
    Mar 2008

    Posted 20 Jan 2011 Link to this post

    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.
  6. Rumen
    Admin
    Rumen avatar
    12846 posts

    Posted 21 Jan 2011 Link to this post

    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.
  7. Steele
    Steele avatar
    96 posts
    Member since:
    Mar 2008

    Posted 24 Jan 2011 Link to this post

    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.
  8. Rumen
    Admin
    Rumen avatar
    12846 posts

    Posted 26 Jan 2011 Link to this post

    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.
  9. Steele
    Steele avatar
    96 posts
    Member since:
    Mar 2008

    Posted 26 Jan 2011 Link to this post

    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.

  10. Steele
    Steele avatar
    96 posts
    Member since:
    Mar 2008

    Posted 27 Jan 2011 Link to this post

    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.
  11. Rumen
    Admin
    Rumen avatar
    12846 posts

    Posted 01 Feb 2011 Link to this post

    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.
  12. Steele
    Steele avatar
    96 posts
    Member since:
    Mar 2008

    Posted 01 Feb 2011 Link to this post

    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.
  13. Daniel
    Admin
    Daniel avatar
    4943 posts

    Posted 07 Feb 2011 Link to this post

    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.
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017