c# - ASP.NET 自定义验证器客户端和服务器端验证未触发

标签 c# .net asp.net validation customvalidator

我以前没有发生过这种情况,但出于某种原因,客户端和服务器端验证事件都没有被触发:

<asp:TextBox ID="TextBoxDTownCity" runat="server" CssClass="contactfield" />
<asp:CustomValidator ID="CustomValidator2" runat="server" EnableClientScript="true"
    ErrorMessage="Delivery Town or City required"
    ClientValidationFunction="TextBoxDTownCityClient" 
    ControlToValidate="TextBoxDTownCity"
    OnServerValidate="TextBoxDTownCity_Validate" Display="Dynamic" >
</asp:CustomValidator>

服务器端验证事件:

protected void TextBoxDTownCity_Validate(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;
}

客户端验证事件:

function TextBoxDCountyClient(sender, args) {
    args.IsValid = false;
    alert("test");
}

我认为至少服务器端验证会触发,但没有。这以前从未发生在我身上。这真的让我难住了。

我查看了输出,ASP.NET 正在识别客户端函数:

ASP.NET JavaScript 输出:

var ctl00_ctl00_content_content_CustomValidator2 = document.all ? document.all["ctl00_ctl00_content_content_CustomValidator2"] : document.getElementById("ctl00_ctl00_content_content_CustomValidator2");

ctl00_ctl00_content_content_CustomValidator2.controltovalidate = "ctl00_ctl00_content_content_TextBoxDTownCity";

ctl00_ctl00_content_content_CustomValidator2.errormessage = "Delivery Town or City required";

ctl00_ctl00_content_content_CustomValidator2.display = "Dynamic";

ctl00_ctl00_content_content_CustomValidator2.evaluationfunction = "CustomValidatorEvaluateIsValid";

ctl00_ctl00_content_content_CustomValidator2.clientvalidationfunction = "TextBoxDTownCityClient";

呈现的自定义验证器:

<span id="ctl00_ctl00_content_content_CustomValidator2" style="color:Red;display:none;">Delivery Town or City required</span> 

谁能解释一下为什么客户端和服务器端验证都不会触发。

编辑:错别字,我粘贴了错误的函数,问题还是一样

只是对最后一条评论的另一个更新:TextBox 的位置不能为空。我对此进行了测试,但事实并非如此。在空白页面上,CustomValidator 在没有值的情况下正常触发了我的客户端验证函数:

<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" 
ErrorMessage="CustomValidator" ClientValidationFunction="TextBoxDAddress1Client"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

最佳答案

使用这个:

<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>

验证一个空字段。

您不需要添加 2 个验证器!

关于c# - ASP.NET 自定义验证器客户端和服务器端验证未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/701029/

相关文章:

c# - 如何使用 string.Substring(char, char) 而不是 string.Substring(int, int)?

c# - SqlDataReader 读入 List<string>

c# - 使用 linq/lambdas 获取不同列表的最快方法

c# - 如何向客户端发送多个文件以供下载

c# - 无法将对象加载到 Asp.net 上的 Redis session 状态提供程序

asp.net - 类型安全编码

c# project-wide 使用别名指令

c# - 简化类道路系统的碰撞网格?

c# - 如何用自动递增的数字替换每一行?

.net - ASP.NET MVC 值得研究吗?