文本框自定义验证
本文关键字:验证 自定义 文本 | 更新日期: 2023-09-27 18:13:34
我已经创建了文本框自定义验证控件,我在我的aspx页面中使用它,它的工作很好,直到找到长度意味着如果它是空的意味着它将正确验证但现在我想加强这一点,比如如果我想输入我的电子邮件id,那么第一个条件是,它不应该是空的,第二是它应该是abc@abc.com的格式。如果它是空的意味着我需要显示错误消息,如"请输入电子邮件id!!"',如果不是上述格式,则显示'请输入正确的电子邮件id!!'。
here is my code,
TextboxCustomValidation.aspx
namespace TextboxCustomValidator
{
public class TextboxCustomValidation : BaseValidator
{
protected override void OnPreRender(EventArgs e)
{
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "CheckTextboxvalid");
this.CreateJavaScript();
}
base.OnPreRender(e);
}
protected void CreateJavaScript()
{
StringBuilder sb = new StringBuilder();
sb.Append(@"<script type=""text/javascript"">function CheckTextboxvalid(ctrl){");
sb.Append(@"var txtlength = document.getElementById(document.getElementById(ctrl.id).controltovalidate);");
sb.Append(@"if(txtlength.value.length>2){");
sb.Append(@"return true; }else");
sb.Append(@" {return false;} ");
sb.Append(@"}</script>");
Page.ClientScript.RegisterClientScriptBlock(GetType(), "JSScript", sb.ToString());
}
protected override bool ControlPropertiesValid()
{
TextBox txt = FindControl(ControlToValidate) as TextBox;
return (txt != null);
}
protected override bool EvaluateIsValid()
{
return CheckTextboxIsValidorNot();
}
protected bool CheckTextboxIsValidorNot()
{
TextBox txtControlName = (TextBox)FindControl(this.ControlToValidate);
if (txtControlName.Text.Length > 0)
return true;
else
return false;
}
}
}
**MyTextBoxValidation.aspx**
<%@ Register TagPrefix="TCV" Namespace="TextboxCustomValidator" %>
<body>
<form id="form1" runat="server">
<div>
UserName :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<TCV:TextboxCustomValidation ControlToValidate="txtUserName" ErrorMessage="Please enter username !!"
EnableClientScript="true" runat="server"></TCV:TextboxCustomValidation>
<asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
<TCV:TextboxCustomValidation ControlToValidate="txtEmailId" ErrorMessage="please enter txtEmailId!!" EnableClientScript="false"
runat="server">
</TCV:TextboxCustomValidation>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save_Click" />
</div>
</form>
</body>
</html>
帮助我,
应该是这样的
public bool ValidateMail(string mailAdress)
{
if (String.IsNullOrEmpty(mailAdress))
{
ShowError("please enter email id!!");
return false;
}
//The regular expression matches at:
//[anything]-@-[anything except "."]-.-[2 or 3 chars after the "."]
else if (!Regex.Match(mailAdress, @".+'@[^'.]+'..{2,3}")
.Length == mailAdress.Length)
{
ShowError("please enter correct email id!");
return false;
}
return true
}