Created
October 27, 2020 21:25
-
-
Save kinetiq/faed1e3b2da4cca922896d1f7cdcc79b to your computer and use it in GitHub Desktop.
Manually validate any model in .NET Core 3.1
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
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations; | |
namespace Ether.Validation | |
{ | |
public static class SimpleValidator | |
{ | |
/// <summary> | |
/// Validate the model and return a response, which includes any validation messages and an IsValid bit. | |
/// </summary> | |
public static ValidationResponse Validate(object model) | |
{ | |
var results = new List<ValidationResult>(); | |
var context = new ValidationContext(model); | |
var isValid = Validator.TryValidateObject(model, context, results, true); | |
return new ValidationResponse() | |
{ | |
IsValid = isValid, | |
Results = results | |
}; | |
} | |
/// <summary> | |
/// Validate the model and return a bit indicating whether the model is valid or not. | |
/// </summary> | |
public static bool IsModelValid(object model) | |
{ | |
var response = Validate(model); | |
return response.IsValid; | |
} | |
} | |
public class ValidationResponse | |
{ | |
public List<ValidationResult> Results { get; set; } | |
public bool IsValid { get; set; } | |
public ValidationResponse() | |
{ | |
Results = new List<ValidationResult>(); | |
IsValid = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment