代码之家  ›  专栏  ›  技术社区  ›  Gaurav

在文本框中阻止任何类型的URL

  •  0
  • Gaurav  · 技术社区  · 7 年前

    我想在用户点击提交按钮后验证textbox值。我想检查一下文本中是否有任何类型的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.com 和 https://www.example.com

    3 回复  |  直到 7 年前
        1
  •  0
  •   fubo    7 年前

    System.Uri 用于验证

    protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
    {
        System.Uri result = null;
        e.IsValid = !System.Uri.TryCreate(e.Value, UriKind.Absolute, out result);
    }
    
        2
  •  0
  •   Mav    7 年前

    ((ht|f)tp(s?)\:\/\/)?[0-9a-zA-Z]([-.\w++]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)? Here's

        3
  •  0
  •   Gaurav    7 年前

    谢谢大家的帮助。最后我用下面的代码解决了

    protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
    {
        string pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
        Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        e.IsValid = !reg.IsMatch(e.Value);
    
    }