Thursday, 30 January 2014

Call Server side method from JQuery in ASP.NET

Description:

In this article, I am going to write different type of examples to Call Server Side method from JQuery Client Side code in ASP.NET.

Summary:


Call Server Side method from JQuery in ASP.NET using JQuery ajax

   You can call server side C# method from JQuery client side using JQuery ajax method in ASP.NET.
Note: You need add reference for JQuery script file to use JQuery ajax.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using JQuery ajax</title>
    <script type="text/JavaScript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="GetServerDate()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate()
    {
        return DateTime.Now.ToLocalTime().ToString();
    }



Call Server Side method from JQuery using JQuery ajax with Parameters

   You can call server side C# method from JQuery in ASP.NET using JQuery ajax method. Here, I have written JQuery ajax example to get current date time by passing parameters.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using JQuery ajax</title>
    <script type="text/JavaScript" 
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"format":"' + format + '"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
            $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate(string format)
    {
        if (format.Equals("utc"))
        {
            return DateTime.Now.ToUniversalTime().ToString();
        }
        else
        {
            return DateTime.Now.ToLocalTime().ToString();
        }
    }


Call Server Side method from JQuery in ASP.NET using PageMethods

   You can call server side method from JavaScript using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True". Here, I have written an example to get web server time using PageMethods with Ajax call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JQuery in ASP.NET using PageMethods</title>
    <script type="text/JavaScript" 
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                $('#currentDate').text(dateTime)
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [System.Web.Services.WebMethod]
   public static string GetServerDate(string format)
   {
       if (format.Equals("utc"))
       {
           return DateTime.Now.ToUniversalTime().ToString();
       }
       else
       {
           return DateTime.Now.ToLocalTime().ToString();
       }
   }


Call Server Side method from JQuery using XMLHttpRequest with Ajax call(Asynchronously)

   The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to get web server current Date Time by using XMLHttpRequest object with Ajax(Asynchronous) call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side C# function from JQuery using
 XMLHttpRequest with Ajax call(Asynchronously)</title>
    <script type="text/JavaScript" 
       src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {                    
                    $('#currentDate').text(xmlhttp.responseText)
                }
            }
            xmlhttp.open("Get", url, true);
            xmlhttp.send();
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
public partial class Default: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }
Note: Don't forgot to include the line Response.Cache.SetCacheability(HttpCacheability.NoCache) to stop page cache, otherwise you will get same result from cached page.


Call Server Side function from JQuery using XMLHttpRequest without Ajax call(synchronously)

   If you want to call web server C# function as Synchronous method (without Ajax call), you need to change value true to false in the line xmlhttp.open("Get", url, true);

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# function from JQuery using XMLHttpRequest
 without Ajax call(synchronously)</title>
    <script type="text/JavaScript" 
         src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            $('#currentDate').text(xmlhttp.responseText)
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }



Call Server Side C# method from JQuery using XMLHttpRequest with Parameters

   You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to call C# web server side function from JQuery using XMLHttpRequest object without Ajax(Synchronous) call and Parameters.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# method from JQuery 
using XMLHttpRequest with Parameters</title>
    <script type="text/JavaScript" 
      src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/JavaScript">
        function GetServerDate(format) {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate&format=" + format;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
             $('#currentDate').text(xmlhttp.responseText)
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
    <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate(Request.QueryString["format"]);
            }
        }

        private void GetServerDate(string dateformat)
        {
            Response.Clear();
            if (dateformat.Equals("utc"))
            {
                Response.Write(DateTime.Now.ToUniversalTime().ToString());
            }
            else
            {
                Response.Write(DateTime.Now.ToLocalTime().ToString());
            }
            Response.End();
        }

Thursday, 23 January 2014

Call Server side method from JavaScript in ASP.NET

Description:

In this article, I am going to write different type of examples to Call Server Side method from JavaScript Client Side code in ASP.NET.

Summary:


Call Server Side method from JavaScript in ASP.NET using PageMethods

   You can call server side method from JavaScript using Ajax ScriptManager's PageMethods. To use this you need to add ScriptManger tag in your page and enable property EnablePageMethods="True". Here, I have written an example to get web server time using PageMethods with Ajax call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using PageMethods</title>
    <script type="text/javascript">
        function GetServerDate(format) {
            PageMethods.GetServerDate(format, OnSuccess, OnFailure);
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="scripman1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
   {
   }

   [System.Web.Services.WebMethod]
   public static string GetServerDate(string format)
   {
       if (format.Equals("utc"))
       {
           return DateTime.Now.ToUniversalTime().ToString();
       }
       else
       {
           return DateTime.Now.ToLocalTime().ToString();
       }
   }


Call Server Side method from JavaScript in ASP.NET using JQuery ajax

   You can call server side C# method from JavaScript client side using JQuery ajax method in ASP.NET.
Note: You need add reference for JQuery script file to use JQuery ajax.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function GetServerDate() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show Server Time" onclick="GetServerDate()" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
   protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate()
    {
        return DateTime.Now.ToLocalTime().ToString();
    }



Call Server Side method from JavaScript using JQuery ajax with Parameters

   You can call server side C# method from JavaScript in ASP.NET using JQuery ajax method. Here, I have written JQuery ajax example to get current date time by passing parameters.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side method from JavaScript in ASP.NET using JQuery ajax</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        function GetServerDate(format) {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetServerDate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"format":"' + format + '"}',
                success: function (result) {
                    OnSuccess(result.d);
                },
                error: function (xhr, status, error) {
                    OnFailure(error);
                }
            });
        }
        function OnSuccess(dateTime) {
            if (dateTime) {
                document.getElementById("currentDate").innerHTML = dateTime;
            }
        }
        function OnFailure(error) {
            alert(error);
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
        <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
        <label id="currentDate">
            This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetServerDate(string format)
    {
        if (format.Equals("utc"))
        {
            return DateTime.Now.ToUniversalTime().ToString();
        }
        else
        {
            return DateTime.Now.ToLocalTime().ToString();
        }
    }



Call Server Side method from JavaScript using XMLHttpRequest with Ajax call(Asynchronously)

   The XMLHttpRequest object is used to exchange data with a server behind the scenes. You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to get web server current Date Time by using XMLHttpRequest object with Ajax(Asynchronous) call.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Call Server Side C# function from JavaScript using
 XMLHttpRequest with Ajax call(Asynchronously)</title>
    <script type="text/javascript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("currentDate").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("Get", url, true);
            xmlhttp.send();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
public partial class Default: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }
Note: Don't forgot to include the line Response.Cache.SetCacheability(HttpCacheability.NoCache) to stop page cache, otherwise you will get same result from cached page.


Call Server Side function from JavaScript using XMLHttpRequest without Ajax call(synchronously)

   If you want to call web server C# function as Synchronous method (without Ajax call), you need to change value true to false in the line xmlhttp.open("Get", url, true);

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# function from JavaScript using XMLHttpRequest
 without Ajax call(synchronously)</title>
    <script type="text/javascript">
        function GetServerDate() {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate";
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("currentDate").innerHTML = xmlhttp.responseText;
        }

    </script>   
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show Server Time" onclick="GetServerDate()" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate();
            }
        }

        private void GetServerDate()
        {
            Response.Clear();
            Response.Write(DateTime.Now.ToString());
            Response.End();
        }
    }



Call Server Side C# method from JavaScript using XMLHttpRequest with Parameters

   You can call server side C# web method from JavaScript client side by using this object without refreshing or reloading the page. Here, I have written example to call C# web server side function from JavaScript using XMLHttpRequest object without Ajax(Synchronous) call and Parameters.

Default.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Server Side C# method from JavaScript 
using XMLHttpRequest with Parameters</title>
    <script type="text/javascript">
        function GetServerDate(format) {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "Default.aspx?Method=GetServerDate&format=" + format;
            xmlhttp.open("Get", url, false);
            xmlhttp.send(null);
            document.getElementById("currentDate").innerHTML = xmlhttp.responseText;
        }

    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Show UTC Server Time" onclick="GetServerDate('utc')" />
    <input type="button" value="Show Local Server Time" onclick="GetServerDate('local')" />
    <label id="currentDate">This is current Date Time in Web Server</label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Method"] == "GetServerDate")
            {
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                GetServerDate(Request.QueryString["format"]);
            }
        }

        private void GetServerDate(string dateformat)
        {
            Response.Clear();
            if (dateformat.Equals("utc"))
            {
                Response.Write(DateTime.Now.ToUniversalTime().ToString());
            }
            else
            {
                Response.Write(DateTime.Now.ToLocalTime().ToString());
            }
            Response.End();
        }

Related Articles:

Saturday, 18 January 2014

Validate Email Address in JQuery

Description:

  In this article, I am going to write JQuery code examples to Validate Email Address in JQuery by using different type of  Regular Expression filters in client side.

Summary:


Validate Email in JQuery using Regular Expression - 1

   You can use and alter the following JQuery function to Check and Validate an Email address, then you can say confirmation to user about the user has entered valid Email ID or not.
<html>
<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /[\w-]+@([\w-]+\.)+[\w-]+/;
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Validate Email in JQuery with Regular Expression</h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 

Validate Email Address in JQuery with Regular Expression - 2

   You can use and alter the following JQuery function to Validate an Email Address from client side.
<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Validate Email ID in JQuery using Regular Expression</h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 

Validate Corporate Email in JQuery using Regular Expression - 3

   You can use the following JQuery function for Domain specific Email validation in JQuery from client side. Here, if you enter the email address with domains gmail.com,yahoo.com,hotmail.com and live.com, the checkMail function throws alert 'Please enter a valid email address'. By using this you can force user to enter only Corporate Email Address and stop user from entering some unwanted Email Domain Address.
<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!live.com)(?!hotmail.com)([\w-]+\.)+[\w-]{2,4})?$/
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Validate Domain specific Email Address in JQuery using Regular Expression</h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 

Email validation in JQuery using Regular Expression - 4

   You can use and alter the following JQuery function to validate and test an Mail Address from client side.
<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Email validation in JQuery using Regular Expression</h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 

Validate case sensitive Email Address in JQuery using Regular Expression - 5

   You can use the following JQuery function to validate Case Sensitive Email Address in JQuery. This function check and allow only lower case letters in email address.
<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Validate case sensitive Email Address in JQuery </h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 


Validate Email in JQuery using Regular Expression - 6

   You can use the following JQuery function to check Email Address is valid or not in JQuery using Regular Expression from client side.
<html>
<head>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
 
function checkEmail() {
 
    var email=$('#txtEmailID').val();
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
 
    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>
 
<h1>Validate Email in JQuery using Regular Expressiont</h1>
 
<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>
 
</body>
</html> 

Validate Email Address in JavaScript

Description:

  In this article, I am going to write JavaScript code examples to Validate Email in JavaScript by using different type of  Regular Expression filters in client side.

Summary:


Validate Email Address in JavaScript using Regular Expression - 1

   You can use and alter the following JavaScript function to Check and Validate an Email address, then you can say confirmation to user about the user has entered valid Email ID or not.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;
    var filter = /[\w-]+@([\w-]+\.)+[\w-]+/;

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Validate Email in JavaScript using Regular Expression</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 


Validate Email Address in JavaScript using Regular Expression - 2

   You can use and alter the following JavaScript function to Validate an Email Address from client side.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Validate Email in JavaScript using Regular Expression</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 


Validate Corporate Email in JavaScript using Regular Expression - 3

   You can use the following JavaScript function for Domain specific Email validation in JavaScript from client side. Here, if you enter the email address with domains gmail.com,yahoo.com,hotmail.com and live.com, the checkMail function throws alert 'Please enter a valid email address'. By using this you can force user to enter only Corporate Email Address and stop user from entering some unwanted Email Domain Address.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;

    var filter = /^([\w-\.]+@(?!gmail.com)(?!yahoo.com)(?!live.com)(?!hotmail.com)([\w-]+\.)+[\w-]{2,4})?$/

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Validate Domain specific Email Address in JavaScript using Regular Expression</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 

Email validation in JavaScript using Regular Expression - 4

   You can use and alter the following JavaScript function to validate and test an Email Address from client side.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;

    var filter = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Email validation in JavaScript using Regular Expression</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 


Validate case sensitive Email in JavaScript using Regular Expression - 5

   You can use the following JavaScript function to validate Case Sensitive Email Address in JavaScript. This function check and allow only lower case letters in email address.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;

    var filter = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Validate case sensitive Mail ID in JavaScript</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 


Validate Email Address in JavaScript using Regular Expression - 6

   You can use the following JavaScript function to check Email Address is valid or not in JavaScript using Regular Expression from client side.
<html>
<head>
<script>

function checkEmail() {

    var email = document.getElementById('txtEmailID').value;

    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!filter.test(email)) {
    alert('Please enter a valid email address');
    return false;
 }
  else{
  alert('Nice!..you have entered valid email address');
  }
}
</script>
</head>
<body>

<h1>Validate Email in JavaScript using Regular Expressiont</h1>

<input type='text' id='txtEmailID'/>
<button type="button" onclick="checkEmail()">Validate Mail</button>

</body>
</html> 

Friday, 17 January 2014

Use of Distinct with Custom Class objects in C#

Description:

    You can get distinct class objects from the list of objects by using Distinct method if the class is C# .NET build-in class like string and int. But when you use Distinct with list of user defined custom class object, you may not get perfect result, to achieve this you need to override Equals and GetHashCode methods.

Use of Distinct with List of Custom Class objects in C#

public class UserDetails : IEquatable<UserDetails>
{
    public string UserName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }

    public bool Equals(UserDetails userDetail)
    {

        //Check whether the compared object is null.  
        if (Object.ReferenceEquals(userDetail, null)) return false;

        //Check whether the compared object references the same data.  
        if (Object.ReferenceEquals(this, userDetail)) return true;

        //Check whether the UserDetails' properties are equal.  
        return UserName.Equals(userDetail.UserName) && City.Equals(userDetail.City)
                && Country.Equals(userDetail.Country);
    }

    // If Equals() returns true for a pair of objects   
    // then GetHashCode() must return the same value for these objects.  

    public override int GetHashCode()
    {

        //Get hash code for the UserName field if it is not null.  
        int hashUserName = UserName == null ? 0 : UserName.GetHashCode();

        //Get hash code for the City field.  
        int hashCity = City.GetHashCode();

        //Get hash code for the Country field.  
        int hashCountry = Country.GetHashCode();

        //Calculate the hash code for the GPOPolicy.  
        return hashUserName ^ hashCity ^ hashCountry;
    }
}
Here, We have override Equals and GetHashCode methods in UserDetails class

static void Main(string[] args)
{
    List<UserDetails> users = new List<UserDetails>();
    UserDetails u1 = new UserDetails { UserName = "User1", City = "London", Country = "UK" };
    UserDetails u2 = new UserDetails { UserName = "User2", City = "SanFrn", Country = "USA" };
    UserDetails u3 = new UserDetails { UserName = "User1", City = "London", Country = "UK" };
    users.Add(u1);
    users.Add(u2);
    users.Add(u3);

    // Distinct returns only two user details
    users = users.Distinct().ToList();
}
Thanks,
Morgan
Software Developer

Wednesday, 1 January 2014

Event id 4625 An Error occured during Logon

Description:

In our new ASP.NET Wep Application, we are using Windows Authentication to validate user credential with Active Directory. This mechanism was worked well for the past few days. But today, we have hosted our ASP .NET Web Application in IIS Web Server with host header. Now, after we have added host header to access Web Application, Windows Credential dialog seems not authenticate user's credential properly. but it was worked well before without host header

Now I am getting an error message even though I provide the valid credentials

Event id 4625 An account failed to log on


After I have analyzed some time, noticed the logon failure event '4625 An account failed to log on' in Security event log

Event ID 4625 Source:

Log Name:      Security
Source:        Microsoft-Windows-Security-Auditing
Date:          27/12/2013 2:07:33 PM
Event ID:      4625
Task Category: Logon
Level:         Information
Keywords:      Audit Failure
User:          N/A
Computer:      myServer.myDomain.local
Description:
An account failed to log on.
Subject:
 Security ID:  NULL SID
 Account Name:  -
 Account Domain:  -
 Logon ID:  0x0
Logon Type:   3
Account For Which Logon Failed:
 Security ID:  NULL SID
 Account Name:  Administrator
 Account Domain:  myDomain
Failure Information:
 Failure Reason:  An Error occured during Logon.
 Status:   0xc000006d
 Sub Status:  0x0
Process Information:
 Caller Process ID: 0x0
 Caller Process Name: -
Network Information:
 Workstation Name: myServer
 Source Network Address: 292.168.1.139
 Source Port:  44721
Detailed Authentication Information:
 Logon Process:  
 Authentication Package: NTLM
 Transited Services: -
 Package Name (NTLM only): -
 Key Length:  0
This event is generated when a logon request fails. It is generated on the computer where access was attempted.
The Subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.
The Logon Type field indicates the kind of logon that was requested. The most common types are 2 (interactive) and 3 (network).
The Process Information fields indicate which account and process on the system requested the logon.
The Network Information fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.
The authentication information fields provide detailed information about this specific logon request.
 - Transited services indicate which intermediate services have participated in this logon request.
 - Package name indicates which sub-protocol was used among the NTLM protocols.
 - Key length indicates the length of the generated session key. This will be 0 if no session key was requested.


Solution:Event id 4625 An account failed to log on

After I have some time, found this issue occurs when the Web site uses Integrated Authentication and has a name that is mapped to the local loopback address.

Check this Microsoft's KB article for further analyze: http://support.microsoft.com/kb/896861