是否可以在单个属性上使用 2 个远程验证属性?
是否可以在视图模型中的单个属性上使用 2 个远程验证属性?
我希望能够执行两项检查,首先检查数据库中是否存在给定的用户 ID,其次检查用户尚未在系统上设置帐户。
我想我总是可以创建一个包含两个测试的自定义属性,但如果可能的话,我宁愿只使用开箱即用的功能并将验证链接在一起。
我无法真正将逻辑组合到一个 JsonResult 中,因为我需要根据验证失败的方式有不同的错误消息,并且 AFAIK 不可能将错误消息与验证结果一起返回?
Is it possible to use 2 remote validation attributes on a single property in a view model?
What I would like to be able to do is perform 2 checks, first that a given user id exists in the DB and second that the user has not already set up an account on the system.
I guess I could always make a custom attribute which has both tests in it, but if possible I would prefer to just use the out of the box functionality and chain the validations together.
I cant really combine the logic together into a single JsonResult, as I need to have different error messages depending on how the validation fails, and AFAIK its not possible to return the error message with the validation result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,您可以使用 MVC3 远程验证返回独特的错误消息。例如,请参阅 http://msdn.microsoft .com/en-us/library/gg508808(v=vs.98).aspx 或 http://deanhume.com/Home/BlogPost/mvc-3-and -远程验证/51。
Actually, you can return a distinctive error message using MVC3 remote validation. See, for example, http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx or http://deanhume.com/Home/BlogPost/mvc-3-and-remote-validation/51.
我不确定您对“开箱即用的功能”有何期望,但您可以创建两个足够简单的属性。在 MVC 3 中,您还可以从
IValidatableObject
派生模型并实现Validate
方法。如果您发现需要,后者使您能够在彼此的上下文中对多个属性执行多次验证。以下是如何实现 ValidationAttribute 并装饰您的属性。您需要其中两个,因此我将其命名为
UsernameExistsAttribute
,我们假设您创建了另一个名为AccountAlreadySetupAttribute
的属性,覆盖相同的IdValid
代码>方法。在您的视图模型中,您可以像这样装饰属性:
这会将您的客户端和服务器端验证连接到 MVC 3 框之外。
I'm not sure what you're expecting in terms of "out of the box functionality," but you can create two attributes simple enough. In MVC 3, you also have the opportunity to derive your model from
IValidatableObject
and implement theValidate
method. The latter provides you the ability to perform multiple validations on multiple properties within the context of one another if you find the need.Here's how you could implement the ValidationAttribute and decorate your property. You'll need two of these, so I'll name this one
UsernameExistsAttribute
and we'll pretend you created another one calledAccountAlreadySetupAttribute
overriding the sameIdValid
method.And in your view model, you decorate the attribute like this:
This will wire up your client and server side validation out of the MVC 3 box.