如何使用 FluentValidation 将字符串验证为 DateTime
使用 FluentValidation,是否可以将 string
验证为可解析的 DateTime
,而无需指定 Custom()
委托?
理想情况下,我想说类似 EmailAddress 函数的内容,例如:
RuleFor(s => s.EmailAddress).EmailAddress().WithMessage("Invalid email address");
所以像这样:
RuleFor(s => s.DepartureDateTime).DateTime().WithMessage("Invalid date/time");
With FluentValidation, is it possible to validate a string
as a parseable DateTime
without having to specify a Custom()
delegate?
Ideally, I'd like to say something like the EmailAddress function, e.g.:
RuleFor(s => s.EmailAddress).EmailAddress().WithMessage("Invalid email address");
So something like this:
RuleFor(s => s.DepartureDateTime).DateTime().WithMessage("Invalid date/time");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并且:
或者您可以编写 自定义扩展方法。
and:
or you could write a custom extension method.
您可以按照与 EmailAddress 完全相同的方式进行操作。
然后
You can do it exactly the same way that EmailAddress was done.
http://fluentvalidation.codeplex.com/wikipage?title=Custom
And then
如果 s.DepartureDateTime 已经是 DateTime 属性;将其验证为 DateTime 是无意义的。
但如果它是一个字符串,达林的答案是最好的。
还有一点要补充的是,
假设您需要将 BeAValidDate() 方法移至外部静态类,以免在每个地方重复相同的方法。如果您选择这样做,则需要将 Darin 的规则修改为:
If s.DepartureDateTime is already a DateTime property; it's nonsense to validate it as DateTime.
But if it a string, Darin's answer is the best.
Another thing to add,
Suppose that you need to move the BeAValidDate() method to an external static class, in order to not repeat the same method in every place. If you chose so, you'll need to modify Darin's rule to be: