65.9K
CodeProject is changing. Read more.
Home

Validating gender dynamically using REGEX

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.60/5 (3 votes)

Apr 19, 2012

CPOL
viewsIcon

23572

Validating gender dynamically using REGEX

Introduction

This is to show how we can validate a gender using REGEX. We can validate whether the gender entered is Male or Female using this code. 

Using the code

The following code illustrate how we can check for gender validation 

protected void btnGender_Click(object sender, EventArgs e)
    {
        if (chkGender(txtGender.Text))
        {
            lblGender.Visible = true;
            lblGender.Text = txtGender.Text;
        }
        else
        {
            lblGender.Visible = true;
            lblGender.Text = "Not a valid Gender";
        }
    }
    public bool chkGender(string strGender)
    {
        bool m_flag = false;
        Match match = Regex.Match(strGender, @"^M(ale)?$|^F(emale)?$");
        bool result = match.Success;
        if (result)
        {
            m_flag = true;
        }
        else
        {
            m_flag = false;
        }
        return m_flag;
    } 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!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>
        <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
        <asp:Button ID="btnGender" runat="server" OnClick="btnGender_Click" Text="Validate" />
    </div>
    <br />
    <asp:Label ID="lblGender" runat="server" Visible="false"></asp:Label>
    </form>
</body>
</html>