带有内置验证器的自定义文本框:服务器端验证未触发
我有一个如下所示的类:
public class TextField : TextBox
{
public bool Required { get; set; }
RequiredFieldValidator _validator;
protected override void CreateChildControls()
{
base.CreateChildControls();
_validator = new RequiredFieldValidator();
_validator.ControlToValidate = this.ID;
if(Required)
Controls.Add(_validator);
}
public override void Render(HtmlTextWriter tw)
{
base.Render(tw);
if(Required)
_validator.RenderControl(tw);
}
}
这已经在始终启用 javascript 的内部应用程序中工作了一段时间。 我最近注意到上游 JavaScript 错误可能会阻止验证器触发,因此服务器端验证应该启动......对吗? 正确的?
因此 Page.IsValid 属性始终返回 true (我什至尝试事先显式调用 Page.Validate() )。
经过一番挖掘,我发现验证器 init 方法应该将验证器添加到页面,但由于我构建它的方式,我认为这种情况不会发生。 因此,客户端验证有效,但服务器端验证无效。
我已经尝试过这个:
protected override OnInit()
{
base.OnInit();
Page.Validators.Add(_validator); // <-- validator is null here
}
但是当然验证器在这里是空的(有时它不是必需的,所以不应该添加它)...但是 OnInit() 对我来说做出这些决定真的很早(Required 属性不会)例如,t 已从 ViewState 加载)。
有想法吗?
I have a class that looks like this:
public class TextField : TextBox
{
public bool Required { get; set; }
RequiredFieldValidator _validator;
protected override void CreateChildControls()
{
base.CreateChildControls();
_validator = new RequiredFieldValidator();
_validator.ControlToValidate = this.ID;
if(Required)
Controls.Add(_validator);
}
public override void Render(HtmlTextWriter tw)
{
base.Render(tw);
if(Required)
_validator.RenderControl(tw);
}
}
This has been working for a while in a internal application where javascript is always enabled. I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?
So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand).
After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens. Thus, client side validation works, but server side validation does not.
I've tried this:
protected override OnInit()
{
base.OnInit();
Page.Validators.Add(_validator); // <-- validator is null here
}
But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).
Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CreateChildControls 基本上用于具有子级的控件。 requiredFieldValidator 就像 TextBox 的兄弟姐妹。
这是适合我的代码:
这是后面的 ASP.NET 页面:
这是 ASPX 代码:
The CreateChildControls is basically for the controls that have childs. RequiredFieldValidator is like a sibling to TextBox.
Here is the code that works for me:
And here it the ASP.NET page behind:
And here is the ASPX code:
验证器必须继承自 BaseValidator。
Validators have to inherit from BaseValidator.