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

New Post: CompositeValidator with client side validation

$
0
0
Apologies for reviving an old discussion but this is the top result on Google for this issue.

Would it be possible to achieve this by registering each base validator's rules with the current validator?

Amendment to RegisterBaseValidator method:
        protected void RegisterBaseValidator<TBase>(IValidator<TBase> validator)
        {
            // Ensure that we've registered a compatible validator. 
            if (validator.CanValidateInstancesOfType(typeof(T)))
            {
                foreach (var validationRule in validator)
                    this.AddRule(validationRule);
            }
            else
            {
                throw new NotSupportedException(string.Format("Type {0} is not a base-class or interface implemented by {1}.", typeof(TBase).Name, typeof(T).Name));
            }
        }
I have tried this successfully with both client side and server side validation. Hopefully i'm not overlooking any other problems this may cause.

New Post: Cross domain concerns

$
0
0
I have a unique name rule and for that to work i need access to all the objects in the model.
  • How do I get the objects into the custom rule?
  • Is there a way to raise an "I WANT Validation for this now" event and then listen to this?
I guess that this can be boiled down to a : how do I handle validation outside the context of the current object.

Source code checked in, #df5e3df1a5f90792d3516455d3114ecfb74cd61e

$
0
0
Fix errors introduced by lazily loading display name

New Post: Non-property oriented validation

$
0
0
Hi

Using Custom is the best way to do this.

Jeremy

New Post: Validation of object hierarchy

$
0
0
Hi

Could you provide more details?

What do you mean when you say that you "can't get it to work?" Do you see an error? Perhaps you could post a small code sample of what you're trying to achieve?

Thanks

Jeremy

New Post: Problem creating custom Date Validator

$
0
0
I'm trying to create my own custom date validator, so I can customise the error message shown to the user when the date they have entered is invalid.

Yet no matter what I try, the standard error message "The field DateOfBirth must be a date." shows up.
Here is my validator...
public class DateValidator : PropertyValidator
    {
        public DateValidator()
            : base("Invalid date.")
        {
        }

        protected override bool IsValid(PropertyValidatorContext context)
        {
            var theDate = context.PropertyValue as DateTime?;

            var result = IsDate(theDate);
            return result;
        }

        protected override FluentValidation.Results.ValidationFailure CreateValidationError(PropertyValidatorContext context)
        {
            var result = new FluentValidation.Results.ValidationFailure(context.PropertyName, "This is an invalid date");
            return result;
        }

        private bool IsDate(DateTime? date)
        {
            if (date == default(DateTime))
                return false;
            return true;
        }
    }
I call the validator using the following rule...
RuleFor(p => p.DateOfBirth).SetValidator(new DateValidator());
Any idea what I am doing wrong?
Thanks

New Post: Problem creating custom Date Validator

$
0
0
Hi

I'm guessing you're using asp.net mvc?

The message you're seeing isn't actually coming from FluentValidation, but is coming from MVC's model binding process, so trying to change FluentValidation to avoid this error won't actually work.

FluentValidation is only invoked after the property values have been set on your model, but this error comes from MVC during the setting of the property, so FluentValidation hasn't actually been executed yet, and isn't something FluentValidation has any control over.

As far as I'm aware, this message isn't something that can be changed...perhaps you could try adding a client-side mask on theninput to enforce a valid date before the form is submitted?

Jeremy

New Post: Problem creating custom Date Validator

$
0
0
Hi Jeremy,

Yes I'm using ASP.NET MVC.
Ok that makes sense, I'll do something client-side.

Cheers for the great validation library.

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?

New Post: NotEmpty for collection is not working

$
0
0
Very useful. It would be nice if there was a way to infer types. But I believe it is a limitation of language.

New Post: client side validation for valiator without default constructor

$
0
0
Hi Jeremy,

Thanks for this great library. If have a validator without default constructor, but a contructor with enum parameter and IxxxService parameter, my understand to fluent validation is, I cannot assign such validator to a model like code below because of no default constructor:
[Validator(typeof(CustomerValidator))]
public class Customer {....}

In this case, how to make default client side supported by fluent validation working when MVC view is created. I only find a post how to handle server side validation when page is posted back:
[HttpPost]
public ActionResult Create(User userData)
{
    var validator = new UserValidator(UserValidator.Mode.Create);

    if (ValidateWrapper(validator, userData, this.ModelState))
    {
        // Put userData in database...
    }
   ....
} .....
http://stackoverflow.com/questions/9626472/fluent-validation-rules-subsets-and-nesting
thanks
Domina

New Post: Fake it easy with Fluent Validation

$
0
0
You would have to "fake" your validator.
var fakeAccountValidator = A.Fake<FakeAccountValidator>();

then

A.CallTo(() => fakeAccountValidator.Validate(A<Account>.Ignored, ruleSet:"Post")).Returns(new ValidationResult());

New Post: client side validation for valiator without default constructor

$
0
0
Hi

If you use the AttributedValidatorFactory in conjunction with the [Validator] attribute, then the validators must have a default constructor. If you want to customise the creation of the validator, then you'd need to use a custom implementation of IValidatorFactory rather than relying on the default.

Jeremy

New Post: Can We Change the Property Value if Error Is generated

$
0
0
Hi Everybody,

For Example I have a TextBox for the Amount Field . In which have the User can input numeric or chars. But Characters are invalid input for that. We can check the validation for the Numeric.

But i need to know that Can we change the field textbox value to zero if any types of error will be generate.

New Post: Can We Change the Property Value if Error Is generated

$
0
0
Hi

This isn't something that FluentValidation itself can do. FluentValidation just performs validation - it doesn't know anything about the UI.

In this case, I'd suggest using some sort of client-side input masking to force only numeric values to be entered. Something like this maybe: http://digitalbush.com/projects/masked-input-plugin/

Jeremy

New Post: MVC 4 Integration

$
0
0
Dear Jeremy, thanks for your greate work! I Love it in MVC. Currenly I started a new project based on Web API. As you said in your last post, you planned to support it in WebApi. I want to know when we can see it? thanks in advance :)

New Post: MVC 4 Integration

$
0
0
Hi

This isn't something that's going to happen at the moment I'm afraid.

I did spend some time looking into it, but don't have the time to implement anything further due to the complexity of getting this working. There were several pull requests that have been submitted that have attempted this, but none of them were complete and would still need a lot of work before they could be brought into FluentValidation.

I am also extremely unhappy with the duplication this would require - Microsoft's poor design decision to duplicate a huge amount of the codebase between WebApi and MVC have led to a very messy API which I'm not very happy supporting in FluentValidation's core.

Jeremy

New Post: Unique Value Validation

$
0
0
Jeremy provided the answer by posting the following link'

http://fluentvalidation.codeplex.com/wikipage?title=Validators&referringTitle=Documentation&ANCHOR#Predicate

If you read the SECOND section of this part of the documentation you will see;

Note that there is an additional overload for Must that also accepts an instance of the parent object being validated. This can be useful if you want to compare the current property with another property from inside the predicate:

Example.
RuleFor(customer => customer.Surname).Must((customer, surname) => surname != customer.Forename)

As you can see the customer entity is passed into the .Must() method as a parameter and is therefore available to the predicate.

So I did not need to create a separate custom validator, I could use an existing method to achieve the validation I required.

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);

New Post: How to add the Property value with the localizemessage

$
0
0
Hi ,

I have a model of Customer . I create Required Validation in FirstName . and it's working fine. But I need to show the StoreName in ErrorMessage when FirstName is blank.

Message Should be like this : {storeName} Firstname is Required.
Viewing all 1917 articles
Browse latest View live


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