[英]How to do validation before form is submitted on client side in ASP.NET
I have an ASP.NET web form with validators that are disabled. 我有一个ASP.NET Web表单,其中包含已禁用的验证程序。 I want to enable validators only AFTER Submit button is clicked and based on if the control is visible or not.
我想仅在单击“提交”按钮后启用验证器,并且基于控件是否可见。
Here is my function: 这是我的功能:
protected void Submit_Click(object sender, System.EventArgs e)
{
if (ddlSite.Visible){
rfvSite.Enabled = true;
base.Validate();
} else {
rfvSite.Enabled = false;
}
The above code is working fine. 上面的代码工作正常。 But now I want to check if page is valid or not.
但现在我想检查页面是否有效。 If the page is Valid then I want to process the form.
如果页面有效,那么我想处理表单。 I don't know how to do this.
我不知道该怎么做。
You have multiple options: 您有多种选择:
Try to split your controls into multiple validation groups , which will only validate the controls in a specific group upon submit. 尝试将控件拆分为多个验证组 ,这些验证组仅在提交时验证特定组中的控件。
Write your own custom validator. 编写自己的自定义验证器。 A custom validator can declare a client validation function and a server validation function.
自定义验证器可以声明客户端验证功能和服务器验证功能。 Creating a custom validator is well-documented .
创建自定义验证器已有详细记录 。
As StevieB mentioned, if you hide the controls server-side, the validators won't be fired. 正如StevieB所提到的,如果隐藏控件服务器端,则不会触发验证器。 If the decision to hide them is made on the client, that's more difficult.
如果隐藏它们的决定是在客户端进行的,那就更难了。
Hook into the client-side validation functions and manipulate the validators. 挂钩客户端验证功能并操纵验证器。 This can be difficult and may require changing internal ASP.Net scripts.
这可能很困难,可能需要更改内部ASP.Net脚本。 Sometimes it's the only way to make web form validation do what you need it to.
有时,这是使Web表单验证执行您需要的唯一方法。 See this question for an example of extending/modifying validator behavior.
有关扩展/修改验证器行为的示例,请参阅此问题 。
Since I'm new to asp.Net c#, I was wondering is someone can give me an example or idea as how to achieve this?
由于我是asp.Net c#的新手,我想知道有人能给我一个例子或想法如何实现这个目标吗?
Consider using ASP.Net MVC instead of web forms. 考虑使用ASP.Net MVC而不是Web表单。 The web forms model is old and "fights" you on tasks like this.
Web表单模型已经过时了,并且会像这样“对战”。 If you are just starting out, I'd suggest at least investigating MVC and see if your time is better spent.
如果你刚刚开始,我建议至少调查MVC,看看你的时间是否更好。
由于这个原因,创建了很多jquery插件: http : //tinyurl.com/qetudk8
I believe if you add a 我相信如果你添加一个
if(Page.IsValid) {
// Code here
}
around the button that is submitting the form, the page should fire off validation errors. 在提交表单的按钮周围,页面应触发验证错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.