首页 > 编程 > .NET > 正文

asp.net MaxLengthValidator 最大长度验证控件代码

2024-07-10 12:42:50
字体:
来源:转载
供稿:网友
代码如下:
/// <summary>
/// TextBox的最大长度验证器,如果是varchar,char字段类型,需要此验证
/// </summary>
[Description("对MaxLength进行验证")]
[ToolboxData("<{0}:MaxLengthValidator runat=server></{0}:MaxLengthValidator>")]
public class MaxLengthValidator : BaseValidator
{
/// <summary>
/// 获取或设置是否为非nvarchar,nchar字段验证
/// </summary>
[DefaultValue(true)]
public bool ValidateForNonNationalField
{
get
{
var data = this.ViewState["ValidateForNonNationalField"];
if (data == null)
{
return true;
}
else
{
return (bool)data;
}
}
set
{
this.ViewState["ValidateForNonNationalField"] = value;
}
}

/// <summary>
/// 构造函数
/// </summary>
public MaxLengthValidator()
{
this.ValidateForNonNationalField = true;
}

protected override bool EvaluateIsValid()
{
var targetControlName = this.ControlToValidate;
if (targetControlName == null)
{
//没有目标验证控件,验证通过
return true;
}

var targetControl = this.NamingContainer.FindControl(targetControlName) as TextBox;
if (targetControl == null)
{
//目标控件不是文本框或不存在,验证通过
return true;
}

var maxLength = targetControl.MaxLength;
var targetValue = this.GetControlValidationValue(targetControlName);
var targetLength = 0;
if (string.IsNullOrEmpty(targetValue))
{
targetLength = 0;
}
else
{
if (this.ValidateForNonNationalField)
{
targetLength = this.GetLengthForNonNationnal(targetValue);
}
else
{
targetLength = targetValue.Length;
}
}

return targetLength <= maxLength;
}

/// <summary>
/// 获得保存为Varchar时,text的长度
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public virtual int GetLengthForNonNationnal(string text)
{
if (string.IsNullOrEmpty(text))
{
return 0;
}

var length = 0;
for (var i = 0; i < text.ToCharArray().Length; i++)
{
var charCode = (int)text[i];

length++;
if (charCode > 255)
{
length++;
}
}
return length;
}

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);

if (this.RenderUplevel)
{
writer.AddAttribute("TargetControlID",
this.GetControlRenderID(this.ControlToValidate));
writer.AddAttribute("ValidateForNonNationalField",
this.ValidateForNonNationalField ? "true" : "false");
writer.AddAttribute("evaluationfunction",
"MaxLengthValidator_Validate");

var targetControl = this.NamingContainer.FindControl(this.ControlToValidate) as TextBox;
if (targetControl != null)
{
var maxLength = targetControl.MaxLength;
writer.AddAttribute("maxlength",
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表