Required Field Validator In Ajax

Mahakgarg
Posted by in ASP.NET AJAX category on for Beginner level | Points: 250 | Views : 7927 red flag

In this example I create a validation control. It checks if the TextBox is Empty it shows the error message.

Introduction


In this article I'll show you how to call a RequiredFieldValidator with the help of AJAX.


Using the code

Step1:- In my case,there are three controls in my .aspx page

  1. TextBox (txtfname).

  2. Label (lblmsg) :-To show the Error Message.

  3. And a Button (btnshow).
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
 <asp:Label ID="lblmsg" runat="server" Text="Please Enter your First Name" Style="color: #ff0000; display:none;"></asp:Label>
   <input id="btnshow" type="button" onclick="ShowValdidator()" value="Enter" />

Note:- Here We set the style of Label (lblmsg) :- display:none :-means the label is not displayed.

Here We call the function ShowValdidator() on the onclick event of btnshow, by this we check the TextBox value and call the Label (error meassage)



Step 2: Call the Function (ShowValdidator()):

In the <head> part write the folowing code:-

<script language="JavaScript" type="text/javascript" >
var xmlHttp
var arr;
function ShowValdidator()
{
      xmlHttp=GetXmlHttpObject()
      var url="Default.aspx"
      url=url+"?fname="+document.getElementById('txtfname').value
      xmlHttp.onreadystatechange=stateChanged
      xmlHttp.open("GET",url,true)
      xmlHttp.send(null)
      return false;
}
function stateChanged() 
 
{ 
 
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 
      { 
 
      var str;
 
      str = xmlHttp.responseText;
 
      if(str=="")
      {
        document.getElementById("lblmsg").style.display='';
 
      }
      else
      {
         document.getElementById("lblmsg").style.display='none';
      }
      }
}     
function GetXmlHttpObject()
 
{ 
 
      var objXMLHttp=null
      if (window.XMLHttpRequest)
      {
      objXMLHttp=new XMLHttpRequest()
      }
      else if (window.ActiveXObject)
      {
      objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
      }
      return objXMLHttp
} 

 </script>
Step 3:- In he .cs page:-

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.QueryString["fname"] != null)
        {
            string fname = Request.QueryString["fname"];
            Response.Clear();
            string str = fname.ToString();
            Response.Write(str);
            Response.End();
        }
    }
}

Thanks for reading, let me know your feedback, comment.


Page copy protected against web site content infringement by Copyscape

About the Author

Mahakgarg
Full Name: Mahak Garg
Member Level: Starter
Member Status: Member
Member Since: 8/27/2011 2:28:41 PM
Country: India
Mahak
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)