Share Blog

Thursday, August 07, 2014

Custom Validator For Email And Mobile Number in Asp.net

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

<!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></title> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <table>
           <tr>
           <td >
          Email</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidator1" runat="server"
                        ControlToValidate="TextBox3" ErrorMessage="Enter Valid Email" Font-Bold="True"
                        ForeColor="Red" onservervalidate="Validate_Email"></asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Mobile</td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidator2" runat="server"
                        ControlToValidate="TextBox4" Display="Dynamic"
                        ErrorMessage="Enter Valid mobile " ForeColor="Red"
                        onservervalidate="Validate_Mobile"></asp:CustomValidator>
                </td>
            </tr>
            <tr>
                  <td >
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" />
                </td>
                <td></td>
            </tr>
        </table>
        </div>
    </form>
</body>

</html>

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

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


    }
  
    protected void Validate_Email(object source, ServerValidateEventArgs e)
    {
        //System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[0-9]+$");
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        e.IsValid = r.IsMatch(TextBox3.Text);
    }
    protected void Validate_Mobile(object source, ServerValidateEventArgs e)
    {
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^[987]+\d{9}$");
        e.IsValid = r.IsMatch(TextBox4.Text);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       
    }
}


No comments:

Post a Comment