I have models and validators:
```
[Validator(typeof(AdressValidator))]
public class Adress {
public string PostalCode { get; set; }
public string Street { get; set; }
}
[Validator(typeof(PersonValidator))]
public class Person
{
public Adress Adress { get; set; }
public bool IsAdress2 { get; set; }
public Adress Adress2 { get; set; }
}
public class AdressValidator : AbstractValidator<Adress> {
public AdressValidator() {
RuleFor(p => p.PostalCode).NotEmpty();
RuleFor(p => p.Street).NotEmpty();
}
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(p => p.Adress).SetValidator(new AdressValidator());
RuleFor(p => p.Adress2).SetValidator(new AdressValidator()).When(p=>p.IsAdress2);
}
}
```
And controlers:
```
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index() {
Person person = new Person() {
Adress = new Adress() {
PostalCode = "12-100",
Street = "Street 13"
},
IsAdress2 = false,
Adress2 = new Adress()
};
return View(person);
}
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) {
return RedirectToAction("OK");
}
return View(person);
}
public ActionResult Ok() {
return View();
}
}
```
Adress2 is always validated.
In Attachments is solution without lib and packages.
Comments: sorry for above but I did not know that's how it works.
```
[Validator(typeof(AdressValidator))]
public class Adress {
public string PostalCode { get; set; }
public string Street { get; set; }
}
[Validator(typeof(PersonValidator))]
public class Person
{
public Adress Adress { get; set; }
public bool IsAdress2 { get; set; }
public Adress Adress2 { get; set; }
}
public class AdressValidator : AbstractValidator<Adress> {
public AdressValidator() {
RuleFor(p => p.PostalCode).NotEmpty();
RuleFor(p => p.Street).NotEmpty();
}
}
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator()
{
RuleFor(p => p.Adress).SetValidator(new AdressValidator());
RuleFor(p => p.Adress2).SetValidator(new AdressValidator()).When(p=>p.IsAdress2);
}
}
```
And controlers:
```
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index() {
Person person = new Person() {
Adress = new Adress() {
PostalCode = "12-100",
Street = "Street 13"
},
IsAdress2 = false,
Adress2 = new Adress()
};
return View(person);
}
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) {
return RedirectToAction("OK");
}
return View(person);
}
public ActionResult Ok() {
return View();
}
}
```
Adress2 is always validated.
In Attachments is solution without lib and packages.
Comments: sorry for above but I did not know that's how it works.