Dai
Dai

Reputation: 155065

Complex form validation (disable validation for child object property)

In my business domain, a "User" entity is associated with a single "Person" entity (so the User instance contains security/login information, but the Person entity contains the person's human contact information).

My ViewModel looks like this:

class UserViewModel {
    [Required]
    public String UserName { get; set; }

    public Int64 PersonId { get; set; }
    public PersonViewModel Person { get; set; }

    public Boolean PersonViewModelIsNew { get; set; }
}

class PersonViewModel {
    [Required]
    public String FirstName;
    [Required]
    public String LastName;
    // etc
}

The web-page allows the visitor to edit a User such that they can replace the User's Person information with either a brand-new Person instance, or an existing Person pulled from the database.

Attached is a screenshot of the form:

Screenshot of the form

The idea is that if the "Another employee" radio-button (maps to "UserViewModel.PersonViewModelIsNew" property) is selected then the validation of the "UserViewModel.Person" members will be disabled.

However ASP.NET MVC doesn't have any concept of validation-groups like WebForms does, so how can I control validation like this?

Upvotes: 0

Views: 794

Answers (2)

Dai
Dai

Reputation: 155065

I suppose this is more of a binding issue than a validation issue (as validation happens after binding).

I found one solution is to mark the ViewModel with [Bind(Exclude="Person")], and in my Action method to do this:

if( model.PersonViewModelIsNew ) {
    TryUpdateModel( model.Person, "Person" );
}

if( !ModelState.IsValid ) return View( model );

// Update DB here

This approach seems to work for now.

Upvotes: 1

Mohammad
Mohammad

Reputation: 1990

The MVC Foolproof Validation project adds some good validation rules that cover some situations not covered by validators included with ASP.NET MVC, like the RequiredIfTrue Validation attribute which appears similar to what you need.

Of course you could have written you custom validation rule if you have special requirements, by inheriting the ValidationAttribute class to create your custom validation attribute, you can also optionally provide validation on the client.

Upvotes: 0

Related Questions