Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Unique Value Validation

$
0
0
How was your PropertyValidator code?

I'm trying to do this right now!

Create a PropertyValidator
public class UniqueValidator<T> : PropertyValidator
    where T: class, IEntity
{
    public UniqueValidator(IRepository<T> repository)
        : base("{PropertyName} já existe!")
    { }

    protected override bool IsValid(PropertyValidatorContext context)
    {
        if (context.PropertyValue == null || string.IsNullOrWhiteSpace(context.PropertyValue.ToString()))
            return true;

        // If {HowToGetId?} > 0, is edit
            // return repository.All().Any(p => p.Id != {HowToGetId?} && p.{HowToGetPropertyByExpression?} == nome)
        // return repository.All().Any(p => p.{HowToGetPropertyByExpression?} == nome)
    }
}
Then RuleBuilderExtensions
public static IRuleBuilderOptions<T, TElement> MustBeUnique<T, TElement, TEntity>(this IRuleBuilder<T, TElement> ruleBuilder, IRepository<TEntity> repository)
    where TEntity : class, IEntity
{
    return ruleBuilder.SetValidator(new UniqueValidator<TEntity>(repository));
}
And usage:
public class RegionalValidator : AbstractValidator<RegionalViewModel>
{
    public RegionalValidator(IRepository<Regional> repositorio)
    {
        RuleFor(p => p.Nome)
            .MustBeValidName()
            .MustBeUnique(repositorio); // How to pass Id of object?
    }
}
__Basically the question is:__

In PropertyValidation, how to get current property to use in Linq Expression?
How to pass (or get) Id of object?

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>