11

Problem:
I trying to validate the nested Model but the data annotation attribute is not executing when the Nested Model Instance create.

public class Model
{
    [Required]
    string MainTitle {get;set;}

    public NestedModel NestedModel { get; set; }
}
public class NestedModel
{
    [Required]
    string SubTitle {get;set;}
}

At The Controller:

public ActionResult GetTitles(Model model)
{
    if(ModelState.IsValid)
    {
       //Submodel is always valid even if the sub-title is null.
    }
}

Doesn't Mvc4 Support it? How can I extend the validation to work with this aspect?

Dvir
  • 3,287
  • 1
  • 21
  • 33
  • 1
    Interesting problem, I have code nearly the same and it works as expected. Are you sure your problem isn't elsewhere? Can we maybe get a look at your View? – Kyle Gobel Oct 01 '13 at 17:29
  • 1
    There is no view. I return string to the screen if "ok" or "error". Are you that it's working for you? The nested model validation? Try to remove the first Required from MainTitle and you will see that it's not working – Dvir Oct 02 '13 at 07:18
  • 1
    Ok, I figure out that if I'm not using View the validator won't be execute. That's strange. because thouse attributes is also for using in code first for databases. – Dvir Oct 03 '13 at 08:26
  • As @KyleGobel expressed, nested validation works outta the box for me too. However, boolean and integers I must declare the property nullable (e.g.`bool?` with `[Required]`) – Michael R Aug 16 '22 at 22:34

1 Answers1

15

I had the same problem. I ended doing this:

public ActionResult GetTitles(Model model)
{
    if(ModelState.IsValid && TryValidateModel(model.NestedModel, "NestedModel."))
    {
       //Submodel will be validated here.
    }
}
JoeTac
  • 176
  • 2
  • 7
  • Thats right answer. I forgot I asked this question haha! but i found a solution at the time ;) – Dvir Mar 26 '15 at 09:50
  • Try to use custom [ValidateObject] See https://stackoverflow.com/questions/2493800/how-can-i-tell-the-data-annotations-validator-to-also-validate-complex-child-pro – RouR Apr 16 '18 at 12:31