0

I have the following view models

public class Step4ViewModel {
  [Required(ErrorMessage="Yes/No Required")]
  public bool? HaveVehicles { get; set; }
  public List<Vehicle> Vehicles { get; set; }
  public Step4ViewModel() {
    this.Vehicles = new List<Vehicle>();
  }
}

public class Vehicle {
    public string Index { get; set; }

    [DisplayName("Registration/Vin")]
    [Required(ErrorMessage="Registration Required")]
    [ValidVehicleRegistrationNumber(ErrorMessage = "Invalid Id Number")]
    public string Registration { get; set; }

    [Required(ErrorMessage="Make Required")]
    public string Make { get; set; }

    [Required(ErrorMessage="Model Required")]
    public string Model { get; set; }

    [Required(ErrorMessage="Year")]
    public string Year { get; set; }

    public Vehicle()
    {
        this.Index = Guid.NewGuid().ToString();
    }
}

The validation works just fine. The problem is that it always works. I only want the validation to fire on vehicles in the collection when the user has indicated that they have vehicles. If HaveVehicles equals false I do not want the validation to fire.

Normally for this sort of validation I would build a custom validator in which I would only return validation errors if HaveVehicles is true. I am unable to do this here because HaveVehicles resides in a parent model which is inaccesible from the within the vehicle object.

One approach I've though of that may work is using a partial view to add/remove the collection from the DOM as null collections aren't validated. If the user selects yes ajax loads a partial view which contains a for loop that iterates over each vehicle and calls another partial view to display it.

Is there a better approach to do this or is something similar to the above my only option?

CodeMonkey
  • 119
  • 4
  • 12
  • If you do not have any vehicles, then why would your collection contain any vehicles (i.e. there should be nothing to validate)? –  Oct 18 '16 at 05:56
  • I can see `HaveVehicles ` and `List` are in same model. – Imad Oct 18 '16 at 06:25
  • Just include an 'Add Vehicle' button that adds a vehicle to the collection and re-parse the validator. Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for an example (your `HaveVehicles` property is probably not even required) –  Oct 18 '16 at 06:26
  • @Imad The list is yes. But the vehicles properties reside in a different property so there is no way to access them from within a custom validator – CodeMonkey Oct 19 '16 at 01:19

0 Answers0