2

According to the spec, complex child properties (aka "nested objects") are validated only if an input is found for one of the nested object's properties.

For example, if Person has properties { string Name, Address HomeAddress } and Address has properties { Street, City }, and an action accepts parameter of type Person, then Person.HomeAddress.Street and Person.HomeAddress.City are only validated if the input form had input editors for those nested properties.

Is there any way I can force MVC to validate nested objects, even if inputs are not found for their properties?

Thanks!

2
  • You just want a null validation then? Commented Jul 26, 2010 at 12:54
  • For example, Person.HomeAddress.Street/City may have Required attributes on them (or any other validation attribute). And also, Person.HomeAddress should not be null. Commented Jul 26, 2010 at 20:35

1 Answer 1

3

I don't think so, since the validation is done with the following code in DefaultModelBinder

protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) {
    Dictionary<string, bool> startedValid = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

    foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null)) {
        string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);

        if (!startedValid.ContainsKey(subPropertyName)) {
            startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
        }

        if (startedValid[subPropertyName]) {
            bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
        }
    }

You could try tricking the model binder by using a hidden form field for the Person.Address property like this

<%= Html.HiddenFor(m => m.Address) %>

or

<%= Html.HiddenFor(m => m.Address.FirstLine) %> //just pick any property

And that may kick off the model binder to do a validation. Although if this does work, then you will not beable to put in a value, since it is a hidden form field, but I believe this is what you want :)

Alternatively you could try and write your own model binder, but from my experience if you start to go against the grain of the MVC framework it will come back to bite you

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.