我已经创建了文本框自定义验证控件,我在我的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>
帮助我, 任何回复手段将不胜感激。
答案 0 :(得分:0)
应该像这样工作
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
}