using System.ComponentModel.DataAnnotations; namespace Landmark.OLA.Models { public static class ModelValidator { public static bool TryValidate(Object data) { try { Validate(data); return true; } catch(Exception) { return false; } } //TODO #231: This will not validate properties of the object passed in - a valid Individual with an invalid Address will be deemed valid. //Controllers do validate all properties. public static void Validate(Object data) { //https://stackoverflow.com/a/3783328/266594 var validationResults = new List(); //Can use this to inform user of exact problems var vc = new ValidationContext(data, null, null); var isValid = Validator.TryValidateObject(data, vc, validationResults, true); if (!isValid) { string validationProblems = String.Join('\n', validationResults); throw new ArgumentException($"{data.GetType()} data is invalid: \n {validationProblems}"); } } } }