Skip to content

Instantly share code, notes, and snippets.

@davidisnotnull
Created May 23, 2018 10:51
Show Gist options
  • Save davidisnotnull/f80916933c828bcd0fc406c37b50ae1b to your computer and use it in GitHub Desktop.
Save davidisnotnull/f80916933c828bcd0fc406c37b50ae1b to your computer and use it in GitHub Desktop.
MVC ViewModel Validation
// Ensure that that ViewModel class inherits IValidatableObject, otherwise
// nought is gonna happen.
public class ViewModel : IValidatableObject
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errors = new List<ValidationResult>();
if (StartDate < EndDate)
errors.Add("The Start Date cannot be earlier than the End Date", new[] { "StartDate" }));
return errors;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment