Sunday, January 12, 2014

Asp.net Server Side Validation - CustomValidator

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!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>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    Enter Number:
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ForeColor="Red" ErrorMessage="Please enter numeric values."
        OnServerValidate="Validate_Numeric" ControlToValidate="TextBox1"></asp:CustomValidator>
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CS : System.Web.UI.Page
{
    protected void Validate_Numeric(object sender, ServerValidateEventArgs e)
    {
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[0-9]+$");
        e.IsValid = r.IsMatch(TextBox1.Text);
    }
}

0 comments:

Post a Comment