Search code examples
c#validation.net-coremodelstate

Many, complex ModelError add


I'm little bit new in .core mvc programming.

I have many date validations.

e.g.:

private void Validations()
{
    if (startDate >= endDate)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    if (startDate < DateTime.Today)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    if (startDate < dateInTheFuture)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }

    var substracted = startDate.Subtract(endDate);

    if (substracted.Days < MinDays)
    {
       ModelState.AddModelError("", "ErrorMessage");
       return;
    }
    
    // and so on
}

Is there any way to make it cleaner or better than this?


Solution

  • You can:

    1. Use validation attributes to write manual validations less
    2. Create your own validation attribute for complex field validation logic
    3. Implement IValidatableObject on your model and move validation code inside model class