c# - 在文本框中阻止任何类型的 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\-\.\?\,\'\/\\\+&%\$#_]*)?");
if(res == true)
{
e.IsValid = false;
}
else
{
e.IsValid = true;
}
}
目前它仅验证http://www.example.com
和 https://www.example.com
。有人可以帮我吗?
解决方案
您可以System.Uri
用于验证
protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
{
System.Uri result = null;
e.IsValid = !System.Uri.TryCreate(e.Value, UriKind.Absolute, out result);
}
推荐阅读
- python - 在 python 中输入许多选项卡的优雅方式
- python - C-Extension:生成器的参考计数
- javascript - 为什么我的 JSPdf npm 包在没有任何更新的情况下破坏了我的应用程序?
- c++ - 堆栈数组c ++的Strcpy行为
- matlab - 在 MATLAB 中的绘图中添加文本
- spring - 与用户一起进行春季安全测试
- java - 如何使用 JOptionPane 设置数组的长度
- r - 基于列数的快速方法和行到数据框
- ios - 使用装有 iOS 13.3 的 iPhone 6S 进行 CallKit 通话时,麦克风无法正常工作
- java - 查找所有整数 p 和 q 的优化方法,使得 2^p*3^q 具有给定的十进制长度