创建具有自验证功能的textbox控件>>>>类中添加客户端脚本,以使验证行为可以不只在服务器端触发,也可以在客户端触发
已成功的代码如下:只有服务器端验证(只能输入一定范围的数字)。
using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Drawing;
namespace Wealth_ControlLibrary
{
/// <summary>
/// VTextBox 的摘要说明。
/// </summary>
public class VTextBox : System.Web.UI.WebControls.TextBox, IValidator
{
private bool _valid = true;
private string _errorMessage = "";
private string _friendlyName = "";
private bool _blankAllowed = true;
private int _minValue = Int32.MinValue;
private int _maxValue = Int32.MaxValue;
private int _value;
public string FriendlyName
{
get{return _friendlyName;}
set{_friendlyName = value;}
}
public bool AllowBlank
{
get{return _blankAllowed;}
set{_blankAllowed = value;}
}
public int MinValue
{
get{return _minValue;}
set
{
_minValue = value;
if(_minValue > _maxValue)
{
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
public int MaxValue
{
get { return _maxValue; }
set
{
_maxValue = value;
if (_minValue > _maxValue)
{
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
public VTextBox()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected override void OnInit(EventArgs e)
{
base.OnInit (e);
Page.Validators.Add(this);
}
protected override void OnUnload(EventArgs e)
{
if(Page != null)
{
Page.Validators.Remove(this);
}
base.OnUnload (e);
}
#region IValidator 成员
public void Validate()
{
// TODO: 添加 VTextBox.Validate 实现
this.IsValid = true;
bool isBlank = (this.Text.Trim() == "");
if (isBlank)
{
if (!AllowBlank)
{
this.ErrorMessage = String.Format("'{0}' " +
"cannot be blank.", this.FriendlyName);
this.IsValid = false;
}
}
else
{
try
{
_value = Int32.Parse(this.Text);
if (_value < this.MinValue)
{
this.ErrorMessage = String.Format("'{0}' cannot " +
"be less than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
if (_value > this.MaxValue)
{
this.ErrorMessage = String.Format("'{0}' " +
"cannot be more than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
}
catch
{
this.ErrorMessage = String.Format("'{0}' " +
"is not a valid integer.", this.FriendlyName);
this.IsValid = false;
}
}
}
public bool IsValid
{
get{return _valid;}
set
{
_valid = value;
if(!_valid)
{
this.BackColor = Color.LightCoral;
}
else
{
this.BackColor = Color.White;
}
}
}
public string ErrorMessage
{
get{return _errorMessage;}
set{_errorMessage = value;}
}
public int Value
{
get { return _value; }
set
{
_value = value;
this.Text = _value.ToString();
}
}
#endregion
}
}