MVC3 使用正则表达式进行不显眼的验证,总是第一次失败,然后工作

发布于 2025-01-05 15:51:12 字数 871 浏览 0 评论 0原文

我正在尝试在集合中项目的属性上使用 DataAnnotations RegularExpression 属性 - Field 对象具有 Formatter 对象的集合,而 Formatter 对象又具有具有 Value 属性的 Attributes 集合。

在我的属性视图模型类中,我有:

[RegularExpression(@"^\d+$", ErrorMessage = "That didn't do what you hoped it would do")]
public string Value { get; set; }

我的视图中有这个:

@Html.TextBoxFor( x => x.Formatters[fmt].Attributes[att].Value )

它产生了这个标记:

<input type="text" value=" " name="Formatters[1].Attributes[0].Value" data-val-regex-pattern="^\d+$" data-val-regex="That didn't do what you hoped it would do" data-val="true" >

所有这些看起来都是正确的,但验证总是第一次失败。如果我在文本框中输入 23 并按 Tab 键退出,它会触发验证事件并告诉我事情没有像我希望的那样进行。如果我返回该字段并输入完全相同的值,它就会起作用。如果我输入字母,它仍然会失败。

任何人都知道我可能做错了什么,或者我可以做些什么来强制验证第一次就表现出来?它似乎与集合有关,因为如果我将相同的验证属性放在顶级属性上,它就会按预期工作。

谢谢!

I'm trying to use the DataAnnotations RegularExpression attribute on a property of an item in a collection - A Field object has a collection for Formatter objects that in turn have a collection of Attributes with a Value property.

Inside my attribute view model class, I have:

[RegularExpression(@"^\d+$", ErrorMessage = "That didn't do what you hoped it would do")]
public string Value { get; set; }

I have this in my view:

@Html.TextBoxFor( x => x.Formatters[fmt].Attributes[att].Value )

and it produces this markup:

<input type="text" value=" " name="Formatters[1].Attributes[0].Value" data-val-regex-pattern="^\d+$" data-val-regex="That didn't do what you hoped it would do" data-val="true" >

All of that seems right, but the validation always fails the first time. If I enter 23 into the textbox and tab out, it fires the validation event and tells me things didn't go like I'd hoped they would. If I go back to the field and enter the exact same value, it works. If I enter letters, it still fails as it should.

Anyone have any idea what I might be doing wrong or what I can do to coerce the validation into behaving the first time around? It seems to be related to the collections somehow because if I put the same validation attribute on a top level property, it works as it should.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女皇必胜 2025-01-12 15:51:12

这个问题似乎与我工作时的笔记本电脑有关。昨晚我将代码下载到家里的其他几台计算机上,一切都按预期运行。

我仍然不确定发生了什么,但我不认为这是社区可以帮助解决的问题 - 除非有人想借给我一把锤子。

感谢您的阅读,也感谢达林(Darin)尝试更深入地挖掘。

This issue appears to be isolated to my laptop at work. I pulled down the code to a couple of other computers at home last night and everything works as expected.

I'm still not sure what's going on, but I don't think this is something the community can help resolve - unless someone wants to loan me a hammer.

Thanks for reading and thanks to Darin for trying to dig deeper.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文