using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
namespace WebControlLibrary
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:TelNumValidator runat=server>
</{0}:TelNumValidator>")
]
public class TelNumValidator : BaseValidator
{
// 定义私有变量,其中_clientFileUrl表示JavaScript文件存储目录
// ValidationExpression表示正则表达式
private string _clientFileUrl = "ClientFiles/";
private const string ValidationExpression = @"(\d{3}-\d{8}|\d{4}-\d{7})";
// 定义属性ClientFileUrl,用于获取或设置脚本相对路径
[
Description("获取或设置脚本相对路径"),
DefaultValue("ClientFiles/"),
Category("Appearance")
]
public string ClientFileUrl
{
get
{ return _clientFileUrl; }
set
{ _clientFileUrl = value; }
}
//重写AddAttributesToRender,为验证控件添加特殊属性evaluationfunction和validationexp
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
if (RenderUplevel)
{
writer.AddAttribute("evaluationfunction", "TelNumValidatorEvaluateIsValid", false);
writer.AddAttribute("validationexp", ValidationExpression);
}
}
//重写EvaluateIsValid方法,定义服务器端验证逻辑
protected override bool EvaluateIsValid()
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue == null)
{
return true;
}
controlValue = controlValue.Trim();
try
{
Match m = Regex.Match(controlValue, ValidationExpression);
return (m.Success && (m.Index == 0) && (m.Length == controlValue.Length));
}
catch
{
return false;
}
}
//重写OnPreRender方法,注册客户端脚本程序
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (RenderUplevel)
{Page.ClientScript.RegisterClientScriptBlock ( typeof(TelNumValidator),
"ClientValidator", GetClientFileUrl ( "ClientValidator.js" ));
}
}
// 实现辅助函数GetClientFileUrl,用于获取JavaScript文件的完整路径
private string GetClientFileUrl(string fileName)
{
string tempClient = String.Format("<script language=\"javascript\" src=\"{0}\"></script>", (ClientFileUrl + fileName));
return tempClient;
}
}
function TelNumValidatorEvaluateIsValid(val)
{
var validationexp = val.validationexp;
var valueToValidate = ValidateTrim(ValidateGetValue(val.controltovalidate));
var rx = new RegExp(validationexp);
var matches = rx.exec(valueToValidate);
return (matches != null && valueToValidate == matches[0]);
}
/* 获取验证目标控件的输入数据 */
function ValidateGetValue(id)
{
var control;
control = document.all[id];
if (typeof(control.value) == "string")
{
return control.value;
}
if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number")
{
var j;
for (j=0; j < control.length; j++)
{
var inner = control[j];
if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true))
{
return inner.value;
}
}
}
else
{
return ValidatorGetValueRecursive(control);
}
return "";
}
/* 去除空格处理 */
function ValidateTrim(s)
{
var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
return (m == null) ? "" : m[1];
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="Sample" Assembly="WebControlLibrary" Namespace="WebControlLibrary" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
<title>实现一个验证控件</title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-size: small;">
<asp:TextBox ID="textbox" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="提交"></asp:Button>
<Sample:TelNumValidator ID="demo1" runat="server" Display="dynamic" ControlToValidate="textbox" Text="请输入有效的电话号码" ErrorMessage="正确的格式为010-12345678或者0123-1234567"></Sample:TelNumValidator>
<br /><br />
<asp:ValidationSummary runat="server" ForeColor="blue" DisplayMode="singleParagraph" HeaderText="错误信息:" ID="ValidationSummary1"></asp:ValidationSummary>
</div>
</form>
</body>
</html>