Skip to content

Instantly share code, notes, and snippets.

@kinetiq
Created October 27, 2020 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kinetiq/faed1e3b2da4cca922896d1f7cdcc79b to your computer and use it in GitHub Desktop.
Save kinetiq/faed1e3b2da4cca922896d1f7cdcc79b to your computer and use it in GitHub Desktop.
Manually validate any model in .NET Core 3.1
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