-
-
Save maxisam/3db9956fef931fa6af6a to your computer and use it in GitHub Desktop.
C# Validation Helper
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; | |
using System.Linq; | |
using System.Runtime.Serialization; | |
namespace JimmyBoh.Common.Exceptions | |
{ | |
public class InvalidModelException : Exception | |
{ | |
public ValidationResult[] ValidationResults { get; set; } | |
public InvalidModelException(IEnumerable<ValidationResult> results) | |
{ | |
ValidationResults = results.ToArray(); | |
} | |
public InvalidModelException(string message) : base(message){ } | |
public InvalidModelException(string message, IEnumerable<ValidationResult> results) : base(message, null) | |
{ | |
ValidationResults = results.ToArray(); | |
} | |
// This constructor is needed for serialization. | |
protected InvalidModelException(SerializationInfo info, StreamingContext context):base(info,context){} | |
} | |
} |
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; | |
using JimmyBoh.Common.Exceptions; | |
namespace JimmyBoh.Common.Extensions | |
{ | |
public static class ValidationHelper | |
{ | |
/// <summary> | |
/// Throws an <seealso cref="JimmyBoh.Common.Exceptions.InvalidModelException">InvalidModelException</seealso> if invalid. | |
/// </summary> | |
/// <param name="instance">The object instance to validate.</param> | |
public static void Validate(object instance) | |
{ | |
List<ValidationResult> results; | |
var isValid = IsValid(instance, out results); | |
if(!isValid) | |
throw new InvalidModelException(results); | |
} | |
public static bool IsValid(object instance) | |
{ | |
var vc = new ValidationContext(instance, null, null); | |
return Validator.TryValidateObject(instance, vc, null, true); | |
} | |
public static bool IsValid(object instance, out List<ValidationResult> results) | |
{ | |
var vc = new ValidationContext(instance, null, null); | |
results = new List<ValidationResult>(); | |
return Validator.TryValidateObject(instance, vc, results, true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment