开发者

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

开发者 https://www.devze.com 2023-02-13 11:11 出处:网络
I want to display an editor for a type User.User contains a field Address of type Address.I made an editor template for the type Address so that it is reusable.

I want to display an editor for a type User. User contains a field Address of type Address. I made an editor template for the type Address so that it is reusable.

I don't want the field Address to be required for creating a user. But some fields are required for Address, for exa开发者_JAVA百科mple 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. I would return only validation errors for User then.

What would be the best way to do this?

Thanks,


I used some code from Simon J Ince of Microsoft. 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. 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.


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.


I have found that more complex custom validation is easier with FluentValidation. The documentation provided is very helpful, and you will be able to achieve your validation goal with this open source validator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号