Using a ValidatorCallout on a CustomValidator Control

Last post 07-11-2008 2:04 AM by ravikant12. 15 replies.

Sort Posts:

  • Using a ValidatorCallout on a CustomValidator Control

    07-31-2007, 1:38 PM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    I am trying to us a CustomValidator control to run some custom (obviously) validation code.  When this is done, I want to use the ValidatorCallout to enunciate the validation error to the textbox.  Sounds simple, right?  Here is the known limitation of the ValidatorCallout control:

    "The callouts do not currently display automatically after a server post-back and will only work for custom validators which utilize client-side validation. Even after a post-back the callout will display when the form is re-validated when a postback is attempted again."

    Because of this, I am trying to write a JavaScript function to call my VB code (as I can't do my validation in JS - my JS sucks).  This works:

     

    <asp:CustomValidator ID="CV_PartNumberExists" runat="server" OnServerValidate="PrimeNumberCheck" ClientValidationFunction="CheckPrime"
         ControlToValidate="PartNumberText" ErrorMessage="b><br />A Part Number is required."></asp:CustomValidator>
    <script language="JavaScript">
    <!--
      function CheckPrime(sender, args)
      {
        var iPrime = parseInt(args.Value);
        var iSqrt = parseInt(Math.sqrt(iPrime));
    
        for (var iLoop=2; iLoop<=iSqrt; iLoop++)
          if (iPrime % iLoop == 0) 
          {
             args.IsValid = false;
             return;
          }
    
        args.IsValid = true;
      }
    // -->
    </script

    ...but all it does is validate that the number I entered was a prime number (I borrowed this from another site).  I want use the JS to call my VB function and have that return whether or not the validation is True.

    I would greatly appreciate any suggestions.  Thank you!

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-05-2007, 11:17 PM
    Answer

     Hi,

    So your question is about accessing a server side method from client side function directly.

    My suggestion is to make the server side method a web service then access it. This is a easy task with the help of ASP.NET Ajax.

    You can refer to this documentation for how:

    http://asp.net/ajax/documentation/live/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

     

    Hope this helps. 

     

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-06-2007, 6:26 PM

    This is a pretty simple process. Like Raymond Wen says you can use a Web Service.  But this is not the web way to do it, accessing remote objects tend to be slower, especially if you're just accessing methods for validation.  ASP.Net 2.0 have a ClientCall back functionality.   Look it up on the net.

    1. All you have to do is implement the ICallbackEventHandler on your page.

    2. Get a ClientScript.GetCallbackEventReference for your Server Method in the Page_Load method

    3. Register your client script that callsback the Server Method using ClientScript.RegisterClientScriptBlock

    4. From your JavaScript code call the server side method.

    I'm rusty on my VB.Net but if you need code in C# I can give you an example.

     

     

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-06-2007, 6:46 PM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    Thanks for the reply.  And yes, any examples you could give me would be appreciated - even if they were in C#.   I understand in concept what I am trying to do, but I am having a hard time coding it to work.

    How to do you "register your client script"?  Again, sorry - I am having a hard time with some of the definitions.

    Thanks in advance,

    Karl

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-07-2007, 2:54 PM

    I made a very simple example for you just now in C# using the Validator Callout Extender and a Custom Validator. Just a little explanation.

    1. The CustomValidator calls a Client side JavaScript function: ValidateTextBox

    2. The client side ValidateTextBox function calls a Server Side Call Back method passing the value of the textbox: YourCallBackMethod

    3. In the Code file, make sure to Implement the ICallbackEventHandler.  This interface have 2 methods: GetCallbackResult and RaiseCallbackEvent.

    4. In the Page Load event you register a clientScriptBlock.

    5. In the RaiseCallbackEvent, process your validation.  NOTE: the eventArgument parameter may contain MORE than one parameters.  Each parameter that you passed from your JavaScript client side method "YourCallBackMethod" will be caught here in a comma delimited fashion.  For example: from JavaScript function: YourCallBackMethod(param1, param2, param3),  from the server side: the eventArgument parameter of the RaiseCallbackEvent will have the values of param1, param2 and param3. 

    6. Enough of that, here's the UI code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="TestPage" %>

    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Using ValidatorCallout Extender with a CustomValidator Control</title>

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

    var resultOfTheCallBack;

     

    function ValidateTextBox(sender, args)

    {

    var textBoxValue = document.getElementById('TextBox1').value;

     

    // call server callback method passing the value in your textbox

    YourCallBackMethod(textBoxValue);

     

    if(resultOfTheCallBack == 'Valid')

    args.IsValid = true;

    else

    args.IsValid = false;

    }

     

    function CallBackEventReference(result, context)

    {

    resultOfTheCallBack = result;

    }

    </script>

    </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <ContentTemplate>

    <asp:TextBox ID="TextBox1" runat="server" /><br />

    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    <asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" Display="None" runat="server"

    ErrorMessage="<b>Invalid Textbox Value</b><br/><br/>This is the text in your Validator Callout Extender error.<br/>"

    ClientValidationFunction="ValidateTextBox" />

    <cc1:ValidatorCalloutExtender

    ID="ValidatorCalloutExtender1"

    TargetControlID="CustomValidator1"

    runat="server" />

    </ContentTemplate>

    </asp:UpdatePanel>

    </div>

    </form>

    </body>

    </html>

    7. Here's the UI server code:

    using System;

    public partial class TestPage : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler

    {

    private string _callBackStatus = null;protected void Page_Load(object sender, EventArgs e)

    {

    if (!IsPostBack)

    {

    // create a call back reference method and then

    string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "CallBackEventReference", "context");

    string yourCallBackScript = "function YourCallBackMethod(arg, context) { " + callBackReference + "; }";

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "YourCallBackMethod", yourCallBackScript, true);

    }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    if (IsValid)

    {

    // do whatever you need to do

    }

    }

    // ICallbackEventHandler Members

    public string GetCallbackResult()

    {

    return _callBackStatus;

    }

    public void RaiseCallbackEvent(string eventArgument)

    {

    // do your validation coding here

    if (eventArgument == "junnark")_callBackStatus = "Valid";

    }

    }

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-07-2007, 2:55 PM

    I made a very simple example for you just now in C# using the Validator Callout Extender and a Custom Validator. Just a little explanation.

    1. The CustomValidator calls a Client side JavaScript function: ValidateTextBox

    2. The client side ValidateTextBox function calls a Server Side Call Back method passing the value of the textbox: YourCallBackMethod

    3. In the Code file, make sure to Implement the ICallbackEventHandler.  This interface have 2 methods: GetCallbackResult and RaiseCallbackEvent.

    4. In the Page Load event you register a clientScriptBlock.

    5. In the RaiseCallbackEvent, process your validation.  NOTE: the eventArgument parameter may contain MORE than one parameters.  Each parameter that you passed from your JavaScript client side method "YourCallBackMethod" will be caught here in a comma delimited fashion.  For example: from JavaScript function: YourCallBackMethod(param1, param2, param3),  from the server side: the eventArgument parameter of the RaiseCallbackEvent will have the values of param1, param2 and param3. 

    6. Enough of that, here's the UI code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="TestPage" %>

    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" >

    <head runat="server">

    <title>Using ValidatorCallout Extender with a CustomValidator Control</title>

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

    var resultOfTheCallBack;

     

    function ValidateTextBox(sender, args)

    {

    var textBoxValue = document.getElementById('TextBox1').value;

     

    // call server callback method passing the value in your textbox

    YourCallBackMethod(textBoxValue);

     

    if(resultOfTheCallBack == 'Valid') args.IsValid = true;

    else

    args.IsValid = false;

    }

     

    function CallBackEventReference(result, context)

    {

    resultOfTheCallBack = result;

    }

    </script> </head>

    <body>

    <form id="form1" runat="server">

    <div>

    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <ContentTemplate>

    <asp:TextBox ID="TextBox1" runat="server" /><br />

    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    <asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" Display="None" runat="server" ErrorMessage="<b>Invalid Textbox Value</b><br/><br/>This is the text in your Validator Callout Extender error.<br/>"

    ClientValidationFunction="ValidateTextBox" />

    <cc1:ValidatorCalloutExtender

    ID="ValidatorCalloutExtender1"

    TargetControlID="CustomValidator1"

    runat="server" />

    </ContentTemplate>

    </asp:UpdatePanel>

    </div>

    </form>

    </body>

    </html>

    7. Here's the UI server code:

    using System;

    public partial class TestPage : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler

    {

    private string _callBackStatus = null;protected void Page_Load(object sender, EventArgs e)

    {

    if (!IsPostBack)

    {

    // create a call back reference method and then

    string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "CallBackEventReference", "context");

    string yourCallBackScript = "function YourCallBackMethod(arg, context) { " + callBackReference + "; }";

    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "YourCallBackMethod", yourCallBackScript, true);

    }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    if (IsValid)

    {

    // do whatever you need to do

    }

    }

    // ICallbackEventHandler Members

    public string GetCallbackResult()

    {

    return _callBackStatus;

    }

    public void RaiseCallbackEvent(string eventArgument)

    {

    // do your validation coding here

    if (eventArgument == "junnark")_callBackStatus = "Valid";

    }

    }

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-07-2007, 3:06 PM

    I forgot.  To test the validator callout and custom validator.  First type "jane" then press enter. The ValidatorCallout appears with an error.

    Now try typing "junnark", the ValidatorCallout does not show.

    Happy Coding.

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-07-2007, 4:12 PM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    Thanks for the excellent code - I will experiment and let you know how I make out.

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-09-2007, 2:21 AM

     Validating Server Side using the Validation Callout Extender with the Custom Validator 

    Here's a better view of the code and a sample page.  http://www.junnark.com/Articles/Article0001.aspx

    Hope this helps.

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-09-2007, 10:04 AM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    Awesome example!  I can tell by the test page that it does exactly what I need.

    However, I am having a problem with it, which probably stems from my translation into VB (which is what I use).  I used a site to translate from C#, but errors are showing up on these two lines:

    Inherits System.Web.UI.ICallbackEventHandler
    'The above line gives me this error:
    ' "'Inherits' can appear only once within a 'Class' statement and can only specify one class."
    
    Dim callBackReference As String = Page.ClientScript.GetCallbackEventReference(this, "arg", "CallBackEventReference", "context")
    'The above line gives me this error:
    ' "Name 'this' is not declared."

     I am not sure how to resolve these.  The ICallbackEventHandler is refered to as the "juice" of the code, and I can see how it is necessary.  I have tried declaring it in different ways, but I can't seem to get it right. 

    I could post all of the code, if you wanted, but everything is as posted on the page you referenced.  Please let me know if you have any suggestions of how to resolve this.

    Thanks again!

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-09-2007, 12:01 PM

    Here's the code in VB.Net

     

    Partial Class TestPage
        Inherits System.Web.UI.Page
        Implements System.Web.UI.ICallbackEventHandler
    
        Dim _callBackResult As String = Nothing
    
        Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
            Return _callBackResult
        End Function
    
        Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
            If eventArgument = "junnark" Then
                _callBackResult = "Valid"
            End If
        End Sub
    End Class
     

     

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-09-2007, 12:03 PM

    PS. You cannot use the keyword this in VB.Net, instead use Me

  • Re: Using a ValidatorCallout on a CustomValidator Control

    08-09-2007, 1:03 PM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    OK, I think we are getting somewhere.  The code you kindly provided now compiles and I see the ValidatorCalloutExtender.  For some reason, I had to pull the items out of the Update panel (?).  I do have some bugs however (again, probably due to my translation errors).

    When I first load the page, and I type something other than "junnark", when I tab off the textbox, the callout is displayed correctly.  However, if I DO enter "junnark", the callout is displayed anyway.  If I set a breakpoint in the RaiseCallbackEvent handler, this is what I see:  As soon as I enter "junnark" and tab off the field, I see the callout popup, then the breakpoint comes up and as I step through the code, it sets the callBackResult to "Valid".  But I think this is "too late", as the callout has already been displayed (?).

    Also, if I enter "junnark", press the button, and then change the value of the textbox to some other value, the callout is NOT displayed and I get an "Object expected" error from the page itself.

    I'm sorry to keep bugging you, but I think I am really close and I would really appreciate your continued feedback.  My complete code is posted below.
    Thank you again!

     

    Partial Public Class _Default
        Inherits System.Web.UI.Page
        Implements System.Web.UI.ICallbackEventHandler
    
        Dim callBackResult As String = Nothing
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    
            If Not IsPostBack Then
                ' create a call back reference method and then 
                Dim callBackReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "CallBackEventReference", "context")
                Dim yourCallBackScript As String = "function YourCallBackMethod(arg, context) { " + callBackReference + "; }"
                Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "YourCallBackMethod", yourCallBackScript, True)
            End If
    
        End Sub
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    
        End Sub
    
        ' ICallbackEventHandler Members 
        Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
            Return callBackResult
        End Function
    
        Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
            If eventArgument = "junnark" Then
                callBackResult = "Valid"
            End If
        End Sub
    
    End Class
      
    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ValidationTest._Default" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> 
    <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml" > 
    <head id="Head1" runat="server"> 
    
        <title>Using ValidatorCallout Extender with a CustomValidator Control</title> 
        <script language="javascript" type="text/javascript"> 
            var resultOfTheCallBack; 
            function ValidateTextBox(sender, args) 
            { 
            var textBoxValue = document.getElementById('TextBox1').value; 
    
            // call server callback method passing the value in your textbox 
            YourCallBackMethod(textBoxValue); 
    
            if(resultOfTheCallBack == 'Valid') 
                args.IsValid = true; 
                else 
                args.IsValid = false; 
                } 
                function CallBackEventReference(result, context) 
                { 
                    resultOfTheCallBack = result; 
            } 
        </script> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" /> 
            <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
                <ContentTemplate> <br />   
                </ContentTemplate> 
            </asp:UpdatePanel> 
            <asp:TextBox ID="TextBox1" runat="server" />
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" 
                Text="Button" OnClick="Button1_Click" />
            <asp:CustomValidator ID="CustomValidator1" 
                ControlToValidate="TextBox1" Display="None" runat="server" 
                ErrorMessage="b><br/><br/>This is the text in your Validator Callout Extender error.<br/>" 
                ClientValidationFunction="ValidateTextBox">
            <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" 
                TargetControlID="CustomValidator1" runat="server" /> 
        </div> 
        </form> 
    </body> 
    </html> 
     
  • Re: Using a ValidatorCallout on a CustomValidator Control

    06-09-2008, 4:27 AM
    • Member
      7 point Member
    • kcg_117
    • Member since 06-05-2008, 5:25 AM
    • Posts 6

    do you have any idea for setting CustomValidator Error Messages from Javascript  ,I am not able to do . my whole page is done need to implement this at earliest i tried in javascript setting errormessage as below

    document.getElementById(source.id).setAttribute("errormessage",strError1);

     and my customvalidator is attached to validatorcallout but at runtime validator callout showing message as "This control is not valid"

    can  you help me in this

     

  • Re: Using a ValidatorCallout on a CustomValidator Control

    06-09-2008, 8:52 AM
    • Member
      79 point Member
    • KarlR
    • Member since 02-02-2007, 3:07 PM
    • Sarasota, FL, USA
    • Posts 182

    Sorry, as I mentioned in an earlier post, my JS is terrible.  Hopefully one of the other people associated with this thread can give you some assistance.

    Sorry I couldn't be more helpful.  Sad

Page 1 of 2 (16 items) 1 2 Next >