Search This Blog

Saturday 25 June 2016

Email validation in Asp.net

Step 1:- Default.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Email</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                    </td>
</tr>
<tr>
                    <td colspan="2">
                        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step 2:- Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }

        #region Validation Methods
        public static bool IsEmail(string strEmail)
        {
            string strPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            Regex objPattern = new Regex(strPattern, RegexOptions.IgnoreCase);
            return objPattern.IsMatch(strEmail);
        }
        #endregion

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                DisplayMessage("Email field cannot be blank.");
                txtEmail.Focus();
                return;
            }
            else
            {
                if (!IsEmail(txtEmail.Text))
                {
                    DisplayMessage("Please enter valid Email Id.");
                    txtEmail.Focus();
                    return;
                }
            }
        }

        #region DisplayMessage
        protected void DisplayMessage(string strMsg)
        {
            strMsg = strMsg.Replace("\r\n""\\n");
            strMsg = strMsg.Replace("\n""\\n");
            strMsg = strMsg.Replace("'""");
            string scriptString = @"<script language=""JavaScript"">";
            scriptString += "alert('" + strMsg + "');";
            scriptString += "</script>";

            ClientScript.RegisterStartupScript(this.GetType(), "Startup", scriptString);
        }
        #endregion
    }
}

No comments:

Post a Comment