简体   繁体   English

如何在asp.net mvc中为复杂类型选择验证?

[英]How to make validation optional for a complex type in asp.net mvc?

I want to display an editor for a type User. 我想为User类型显示一个编辑器。 User contains a field Address of type Address. 用户包含类型为Address的字段地址。 I made an editor template for the type Address so that it is reusable. 我为类型Address创建了一个编辑器模板,以便它可以重用。

I don't want the field Address to be required for creating a user. 我不希望创建用户需要字段Address。 But some fields are required for Address, for example country, state etc. 但是地址需要一些字段,例如国家,州等。

I want to validate Address if I receive any data for it, if I don't receive anything, then I don't want to return any validation error to the UI for Address. 我想验证地址,如果我收到任何数据,如果我没有收到任何东西,那么我不想将任何验证错误返回到地址的UI。 I would return only validation errors for User then. 我只会返回User的验证错误。

What would be the best way to do this? 最好的方法是什么?

Thanks, 谢谢,

I used some code from Simon J Ince of Microsoft. 我使用了Microsoft的Simon J Ince的一些代码。 He has it here on his blog. 他是这里在他的博客。 It also has client side validation which is also nice. 它还有客户端验证,这也很好。 It has a RequiredIf attribute that only makes a field required if another field has a certain value. 它有一个RequiredIf属性,如果另一个字段具有特定值,则只需要一个字段。 Just being able to see how he implemented it helped me figure out how to do some of this stuff by myself and I even retrofitted it to allow multiple values. 只是能够看到他如何实现它帮助我弄清楚如何自己做一些这些东西,我甚至改装它以允许多个值。

I have found that more complex custom validation is easier with FluentValidation . 我发现使用FluentValidation可以更轻松地进行更复杂的自定义验证。 The documentation provided is very helpful, and you will be able to achieve your validation goal with this open source validator. 提供的文档非常有用,您可以使用此开源验证程序实现验证目标。

You might want to look into a Custom Model Binder for your User type. 您可能希望查看用户类型的自定义模型绑定器。 That way you can choose to override the validation of the Address item inside a User. 这样,您可以选择覆盖用户内的Address项的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM