Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Created March 16, 2015 06:10
Show Gist options
  • Save danielmackay/cf1abb0aad0c355ef60c to your computer and use it in GitHub Desktop.
Save danielmackay/cf1abb0aad0c355ef60c to your computer and use it in GitHub Desktop.
Extension methods that help convert Fluent Validation errors into MVC Model State errors.
public static class ModelStateCollectionExt
{
public static void Update(this ModelStateDictionary modelState, ValidationResult result, bool usePropertyNames = false)
{
if (result.IsValid)
return;
foreach (var error in result.Errors)
{
// If we exclude the property name the error will show up in the validation summary
var propertyName = usePropertyNames ? error.PropertyName : "";
modelState.AddModelError(propertyName, error.ErrorMessage);
}
}
public static void Update(this ModelStateDictionary modelState, DbEntityValidationException ex)
{
foreach (var property in ex.EntityValidationErrors)
{
foreach (var error in property.ValidationErrors)
{
// Exclude property name so that errors show up in the validation summary
modelState.AddModelError("", error.ErrorMessage);
}
}
}
public static void AddModelError<TModel>(this ModelStateDictionary modelState, Expression<Func<TModel, object>> expr, string error)
{
var propertyName = ExpressionHelper.GetExpressionText(expr);
modelState.AddModelError(propertyName, error);
}
}
@DanElliott
Copy link

What namespace do I import or library do I reference for the ValidationResult type? I ask because I tried System.ComponentModel.DataAnnotations, but IsValid is not a member of ValidationResult.

@MovGP0
Copy link

MovGP0 commented Jul 30, 2018

you have to install the FluentValidation NuGet Package:

install-package FluentValidation

than use this namespace:

using FluentValidation.Results;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment