We help IT Professionals succeed at work.

asp.net client side validation by calling page method

OHHIITSSEAN
OHHIITSSEAN asked
on
Dear asp.net gurus:

I have a asp.net web page where I need user enter product serial number, and I need to validate the user's entry; if the serial number already exists in SQL server database, then asp.net validator will display error message like 'serial number has been used'. I do not want to do this check on the clientvalidation. I knew that can be done by creating a javascript calling a asp.net static page method and then return the isvalid value to validator. The isvalid value is exchange by using JSON serialization?

I just wonder if anybody can give me some example and source code  to show me how to implement the way I want it to be.

Please do not just copy and paste some links to me, please give me some explananation and then I can know how to integrate with my project.

Thanks in advance.

Shawn


Comment
Watch Question

saritapatelSoftware developer

Commented:
textbox validation at serverside
------------------------------------------------------------


using System.Text.RegularExpressions;


#region securitycodebysarita
      int Invalidtext;
    Regex rx = new Regex("[^a-zA-Z0-9:$@.!_/\\~,#&*()=+{}<>?| \\s]");
   
   private void Txt_Validation(Control ControlContainer)
    {
        try
        {
            foreach (Control Ctl in ControlContainer.Controls)
            {
                if ((Ctl.Controls != null))
                {
                    Txt_Validation(Ctl);
                    if (Ctl is System.Web.UI.WebControls.TextBox)
                    {
                        try
                        {
                            TextBox tx = new TextBox();
                            tx = (TextBox)Ctl;

                            if ((rx.IsMatch(tx.Text)))
                            {
                                Invalidtext = Invalidtext + 1;
                             
                                string StrScript = "";
                                StrScript = "<script type='text/javascript'>alert('Invalid Input Character!'); </script>";
                                System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", StrScript, false);

                                return;
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

   
    #endregion
 ******************put this code before any save or update.this will validate all your textbox ******************
   
     Invalidtext = 0;
        Txt_Validation(this);
        if (Invalidtext > 0)
        {
            Invalidtext = 0;
            return;
        }

Note : Change new Regex("[^a-zA-Z0-9:$@.!_/\\~,#&*()=+{}<>?| \\s]"); as per your requirement.
OHHIITSSEANProgrammer

Author

Commented:
Hello saritapate:

Thanks for your prompt response.

Like I said, I need to check if the serial number exists in the serial number registration table of SQL server, your workaround is not the implementation I want. I need a something like asp:customvalidator onclientvalidation calling a javascript whose function can call asp.net static page method, the page method can communication with SQL server, checking if the record already exists or not, then sending the ture/false value to javascript and then javascript can determine if isvalid is true or false and notify customvalidator.

Thanks for your time and support.

Sean
OHHIITSSEANProgrammer

Author

Commented:
Hello ASP.Net gurus:

Anyone have ideas?

Commented:
Well I setup a sample, but I'm not messing with <asp:customvalidators> and pagemethods. The validators just complicate the matter too much.

<see snippet>
****ASPX PAGE****
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethodValidation.aspx.cs" Inherits="PageMethodValidation" %>

<!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>PageMethod Validation</title>

	<script type="text/javascript">
    	
    	function ValidateInput()
    	{
    	
    		var txtBx = $get('<%=TxToValidate.ClientID %>');
    	
    	
    		//Call our function from code behind
    		//If there are no errors it will be picked up by the onSuccess function
    		//If there is an exception it will be picked up by the onFail function
    		PageMethods.ValidateFromPageMethod(txtBx.value, onSuccess, onFail, txtBx);
    	}
    	
    	
    	//Ajax return method
    	//rValue is the return value from the pagemethod
    	//userContext is a pass-through variable(optional) that I sent with the pagemethod
    	//in this case userContext is the txtbox
    	//methodName is the name of the pagemethod (if I wanted to use it)
    	function onSuccess(rValue, userContext, methodName)
		{
			if(!rValue)
			{
				userContext.style.backgroundColor = 'red';
				$get('ErrorMsg').innerHTML = 'Incorrect!';
			}
			else
			{
				userContext.style.backgroundColor = '';
				$get('ErrorMsg').innerHTML = '';
			}
		}
		
		//simply fires if there is an AJAX error
		 function onFail(exValue, rParam, methodName)
		 {
			alert(exValue);
		 }
	</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
    <div>
		<span>Must Be 12345</span><br />
		<asp:TextBox ID="TxToValidate" runat="server" />
		<asp:Button id="Button1"
           Text="Validate" 
           runat="server" OnClientClick="ValidateInput(); return false;" />
	
		<div id="ErrorMsg" style="color:Red;"></div>
    </div>
    </form>
</body>
</html>


***CODE BEHIND****
using System.Web.Services;

public partial class PageMethodValidation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    //Note the addition of the System.Web.Services reference
    //Must be decorated with the WebMethod attribute
    //Must be static
    //Does not have to return a value, but in this case for full demonstation value I've included one.
    [WebMethod]
    public static bool ValidateFromPageMethod(string eArg)
    {
        bool rValue = true;
        if (eArg != "12345") rValue = false;
        return rValue;
    }
}

Open in new window

OHHIITSSEANProgrammer
Commented:
Dear ddayx10:

Thanks for your solution. Your explanatiion is very clear.

OHHIITSSEANProgrammer

Author

Commented:
Thanks ddayx10.

Commented:
YW :)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.