Created
March 16, 2015 06:10
-
-
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.
This file contains hidden or 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
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); | |
} | |
} |
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
What namespace do I import or library do I reference for the
ValidationResult
type? I ask because I triedSystem.ComponentModel.DataAnnotations
, butIsValid
is not a member ofValidationResult
.