![]() 图1 效果图(输入错误状态下) |
| 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 :TelNumValidator runat=server> </:TelNumValidator>") ] public class TelNumValidator : BaseValidator { // 定义私有变量,其中_clientFileUrl表示JavaScript文件存储目录 // ValidationExpression表示正则表达式 private string _clientFileUrl = "ClientFiles/"; private const string ValidationExpression = @"(d-d|d-d)"; // 定义属性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=""></script>", (ClientFileUrl + fileName)); return tempClient; } } |
用户评论