public
Last active

A set of standard extension that help implment data annotations validation

  • Download Gist
ValidationExtensions.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
 
namespace Utilities.Validation.ExtensionMethods
{
public static class ValidationExtensions
{
/// <summary>
/// Validate if the model is valide using its own data annotation
/// </summary>
/// <param name="validate">object to validate</param>
/// <returns><c>true</c> if model is valide <c>false</c> if model is invalide</returns>
public static bool TryValidate(this object validate)
{
return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), null);
}
 
/// <summary>
/// Validate if the model is valide using its own data annotation
/// </summary>
/// <param name="validate">object to validate</param>
/// <param name="validationResults"><c> outs a set of validation errors</c> </param>
/// <returns><c>true</c> if model is valide <c>false</c> if model is invalide</returns>
public static bool TryValidate(this object validate, out ICollection<ValidationResult> validationResults)
{
validationResults = new Collection<ValidationResult>();
return Validator.TryValidateObject(validate, new ValidationContext(validate, null, null), validationResults);
}
 
/// <summary>
/// Combine validation results erros into a single formatted
/// </summary>
/// <param name="validationResults">A set of Validation results to combine </param>
/// <returns>The combined error message</returns>
public static string CombinedErrorMessage(this ICollection<ValidationResult> validationResults)
{
var combine = "Error Validating";
 
foreach (var v in validationResults)
{
combine += v.MemberNames;
combine += ": ";
combine += v.ErrorMessage;
combine += Environment.NewLine;
}
 
return combine;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.