Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created March 29, 2020 13:06
Show Gist options
  • Save luisdeol/333307fb059c136b7b98c9dab5e9a219 to your computer and use it in GitHub Desktop.
Save luisdeol/333307fb059c136b7b98c9dab5e9a219 to your computer and use it in GitHub Desktop.
3.1: Manage data integrity
using _31_ValidateAppInput.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace _31_ValidateAppInput
{
class Program
{
static void Main(string[] args)
{
var student = new Student("l", 5);
var entityErrors = Validator<Student>.Validate(student);
Console.WriteLine($"Errors: {string.Join(", ", entityErrors)}");
Console.ReadLine();
}
}
public static class Validator<T>
{
public static IList<string> Validate(T entity)
{
var validationResults = new List<ValidationResult>();
var validationContext = new ValidationContext(entity, null, null);
Validator.TryValidateObject(entity, validationContext, validationResults, validateAllProperties: true);
return validationResults.Select(v => v.ErrorMessage).ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment