首页 > 解决方案 > 在文本框中阻止任何类型的 URL

问题描述

我想在用户单击提交按钮后验证文本框值。我想检查文本中是否存在任何类型的 URL。如果它存在,它应该抛出一个错误。我需要阻止所有类型的 URL

example.com
www.example.com
http://example.com
http://www.example.com
https://www.example.com

HTML 代码:

<div>
    <asp:TextBox ID="Textbox1" runat="server" ></asp:TextBox>
    <asp:CustomValidator runat="server" OnServerValidate="ValidateNoUrls" ControlToValidate="Textbox1" ErrorMessage="URLs not allowed" />
    <asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Sbumit"/>
</div>  

后端代码:

protected void btnsubmit_Click(object sender, EventArgs e)
{
    if(Page.IsValid)
    {
        Response.Write("Textbox Validated");
    }
}
protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
{
    bool res ;
    res = Regex.IsMatch(e.Value, @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w++]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?");

    if(res == true)
    {
        e.IsValid = false;
    }
    else
    {
        e.IsValid = true;
    }
}

目前它仅验证http://www.example.comhttps://www.example.com。有人可以帮我吗?

标签: c#asp.netregex

解决方案


您可以System.Uri用于验证

protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
{
    System.Uri result = null;
    e.IsValid = !System.Uri.TryCreate(e.Value, UriKind.Absolute, out result);
}

推荐阅读