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

New Post: Unique Value Validation

$
0
0
Hello TetleyK, I read the second part of the documentation.
But as you can see in my code I do not use Must.

My goal is to encapsulate all this logic duplicate field in a custom validation.
I even try to create Expression linq to achieve this goal:
protected override bool IsValid(PropertyValidatorContext context)
{
    if (context.PropertyValue == null || string.IsNullOrWhiteSpace(context.PropertyValue.ToString()))
        return true;

    var currentId = Expression.Lambda<Func<int>>(PropertyId).Compile()(); // Get Current ID

    // p => p.Id != currentId
    ParameterExpression pId = Expression.Parameter(typeof(int), "Id");
    ConstantExpression cId = Expression.Constant(currentId, typeof(int));
    BinaryExpression notCurrent = Expression.NotEqual(pId, cId);
    Expression<Func<int, bool>> NotCurrentExpr =
        Expression.Lambda<Func<int, bool>>(
            notCurrent,
            new ParameterExpression[] { pId });
            
    // p.{PropertyName} == context.PropertyValue
    ParameterExpression pUnique = Expression.Parameter(typeof(string), context.PropertyName);
    ConstantExpression cUnique = Expression.Constant(context.PropertyValue, typeof(string));
    BinaryExpression checkUnique = Expression.Equal(pId, cId);
    Expression<Func<string, bool>> CheckUniqueExp =
        Expression.Lambda<Func<string, bool>>(
            checkUnique,
            new ParameterExpression[] { pUnique });

    if (currentId > 0)
    {
        var exp = Expression.And(NotCurrentExpr, CheckUniqueExp);
        return Repository.All().Provider.CreateQuery(exp);
    }
    return Repository.All().Any(checkUnique);
}
I've used this logic before (with Must and method overload) for validation of unique fields. But with so many fields with this same validation decided to encapsulate

Usage:
RuleFor(p => p.CNPJ)
    .MustBeUnique(p => p.Id, repository);

Viewing all articles
Browse latest Browse all 1917

Trending Articles



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