Created
May 9, 2022 09:56
-
-
Save woeterman94/3529b507527db45c9a7f6013495a95b3 to your computer and use it in GitHub Desktop.
Validate object in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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