Skip to content

Instantly share code, notes, and snippets.

@woeterman94
Created May 9, 2022 09:56
Show Gist options
  • Save woeterman94/3529b507527db45c9a7f6013495a95b3 to your computer and use it in GitHub Desktop.
Save woeterman94/3529b507527db45c9a7f6013495a95b3 to your computer and use it in GitHub Desktop.
Validate object in C#
/// <summary>
/// Method to run modelvalidation. Will return a bad request exception with the validation messages.
/// </summary>
/// <param name="object">The object to validate</param>
/// <exception cref="BadRequestException">400 exception including the validation messages</exception>
private void Validate(object @object)
{
var results = new List<ValidationResult>();
var valid = Validator.TryValidateObject(@object, new ValidationContext(@object), results, validateAllProperties: true);
var errorMessages = results.Select(x => x.ErrorMessage);
if (!valid)
{
throw new BadRequestException(string.Join(" ", errorMessages));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment