1

My question is very similar to a previous question been asked in the following link,

MVC3 unobtrusive validation group of inputs

Basically I need to validate 3 or more input fields (required at lest one). For example I have Email, Fax, Address. Define as follow:

public class MyViewModel
{ 
    public string Email { get; set; }
    public string Fax { get; set; }
    public Address Address { get; set; }
}

public class Address 
{ 
    public string Street { get; set; }
    public string Suburb { get; set; }
}

I need the either Email, Fax or Address.Suburb to be filled in and if this fails, I want all the fields to be highlighted instead of just one field (which is what the solution in previous link contains).

Note, I've got all the server side validation working, I just need to know how would I need this to be done on my client side using MVC3 unobtrusive.

Community
  • 1
  • 1
Jack
  • 2,600
  • 23
  • 29

1 Answers1

2

You could try applying the AtLeastOneRequired attribute on all properties:

public class MyViewModel
{
    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Email { get; set; }

    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Fax { get; set; }

    [AtLeastOneRequired("Email", "Fax", "Phone", ErrorMessage = "At least Email, Fax or Phone is required")]
    public string Phone { get; set; }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for replying, Darin. I've updated my question to include some of the details. Basically, I wasn't able to applied the method you described in the scenario I described above, since the "Address" object doesn't know about class that's referencing it. Is there any other ways of doing it? Is there any good article that you know of which explains how unobtrusive validation works on the client side? – Jack Aug 24 '12 at 07:51
  • @Jack, then use a view model to flatten the structure so that `Email`, `Fax`, `AddressStreet` and `AddressSuburb` are all properties that are part of your main view model. – Darin Dimitrov Aug 24 '12 at 07:53