当我需要在验证失败时修改 HTML 时,是否可以使用 ASP.NET 验证控件?
假设我在 ASP.NET 页面上的文本框有以下 HTML:
<div class="myClass">
<asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>
像这样向该页面添加必填字段验证器是很容易的。
<asp:RequiredFieldValidator ID="valMyTextBox" runat="server" ControlToValidate="txtMyTextBox" ErrorMessage="My Text Box is required."></asp:RequiredFieldValidator>
但如果此文本框验证失败,我需要稍微修改 HTML。我需要向 DIV 添加一个 CSS 类。因此,如果用户将此字段留空,我需要 HTML 如下所示:
<div class="myClass error">
<asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>
这可能吗?我不知道是否有一种方法可以在后面编写代码,只有在这个特定的验证器控件验证失败或其他情况时才会触发。我知道我可以编写在整个页面无效时运行的代码。但我只想当此验证器返回无效时运行此代码。希望这是有道理的。
科里
Let's say that I have the following HTML for a text box on an ASP.NET page:
<div class="myClass">
<asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>
It is easy enough to add a required field validator to this page like this.
<asp:RequiredFieldValidator ID="valMyTextBox" runat="server" ControlToValidate="txtMyTextBox" ErrorMessage="My Text Box is required."></asp:RequiredFieldValidator>
But I need to modify the HTML slightly if this text box fails validation. I need to add a CSS class to the DIV. So if the user leaves this field blank I need the HTML to look like this:
<div class="myClass error">
<asp:TextBox ID="txtMyTextBox" runat="server"></asp:TextBox>
</div>
Is this possible? I can't figure out if there is a way to write code behind that only fires if this particular validator control fails validation or something. I know I can write code that runs when the entire page is not valid. But I just want this code to run when this validator returns invalid. Hope this makes sense.
Corey
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,我认为这可能会有所帮助,尽管我不确定执行此操作的确切方法
,该函数将位于您将调用以根据文本框更改类名称的服务器上
OK I think this might help even though I am not to sure on the exact ways to do this
that function which would be on the server that you would call to change the name of the class depending on the text box
实际上我在另一个 StackOverflow 问题中找到了答案。您可以在这里看到它: 如何在周围的 DIV 上添加额外的 CSS 类以应对失败的表单验证?。
Actually I found the answer in a different StackOverflow question. You can see it here: How do I add an additional CSS class on a surrounding DIV for failed form validation?.
另一种无需回发的方法是覆盖默认的 asp.net 验证脚本。我在这里发布了一个示例:https://stackoverflow.com/a/9857696/618044
Another way to do it without Postback is to override the default asp.net validation scripts. I posted an example here: https://stackoverflow.com/a/9857696/618044