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

Created Unassigned: .SetCollectionValidator in VS2008 [7163]

$
0
0
Hi,

I'm trying to use fluent validation in VS2008.
My problem is that, ServiceStack.FluentValidation.IRuleBuilderInitial() does not contain a definition for 'SetCollectionValidator'.

The same code in Vs2012 works fine.



Thanks

Commented Unassigned: .SetCollectionValidator in VS2008 [7163]

$
0
0
Hi,

I'm trying to use fluent validation in VS2008.
My problem is that, ServiceStack.FluentValidation.IRuleBuilderInitial() does not contain a definition for 'SetCollectionValidator'.

The same code in Vs2012 works fine.



Thanks
Comments: If you're using vs2008 then this will be an old version of FluentValidation from before SetCollectionValidator was introduced. However, you should be able to use SetValidator with the same effect.

New Post: Validate a Collection Object

$
0
0
Is it possible to validate an object that is a Collection? I've used it where a collection is a property in a class. I know I could enumerate through the collection and validate each object contained within, however, I was hoping to fire off validation on the collection as a whole and get results. I already have a validator defined for the object type itself, just not on the collection.

New Post: Validate a Collection Object

$
0
0
Not really...FluentValidation is designed to work by validating a single object (such as a view-model that represents a screen) from which all other objects hang off as properties. I'd suggest either introducing a top-level object or by iterating through the collection and validate each item individually.

New Post: Validate a Collection Object

$
0
0
What if it is a single object that inherits from Collection<>? Would it be possible to apply the contained object type validator to all of the objects? For example, what if I wanted to have an OrderCollection object and also a OrderCollectionValidator where there is a rule that applies OrderValidator to the contents of the collection so that I could just run the Validate off of OrderCollectionValidator and it would validate each of the contained objects. I've been trying with the collection validator off of the single object that is a collection.
public class OrderCollection : Collection<Order>
{
}

New Post: Anyway to get error message within a custom PropertyValidator

$
0
0
Hi, I'm currently trying to create a custom PropertyValidator which is working server side.

Now I'm trying to implement IClientValidatable but need the error message.


UPDATE: found out you can get it via context.Rule.CurrentValidator.ErrorMessageSource.GetString(). Im doing this in the IsValid override which means it's not getting added on the client until after a post.

Am I trying to the client stuff in the wrong place?

New Post: Anyway to get error message within a custom PropertyValidator

$
0
0
Hi

Yes, this is the best way to do it. This is how the built-in rules get the error messages for use with clientside validators. The caveat is the messages cannot contain runtime placeholders.

New Post: Validate a Collection Object

$
0
0
So technically you could have a validator for OrderCollection that then uses RuleFor(x => x).SetValidator(), but I think this would mess up the automatic property name tracking (not sure - I haven't tried it, but might be worth a go)

New Post: AutoFac IoC validators Issue

$
0
0
This worked for me; I know this is slightly off topic but could someone help me with this ?

I have an abstract class which inherits from AbstractValidator thus :

``` public abstract class BaseValidator<T> : AbstractValidator<T>, IBaseValidator<T> where T : class, new()
{
    public ValidationResult ValidateAll(T instance)
    {
        return this.Validate(instance, ruleSet: "*");
    }

    public ValidationResult Validate(T instance, params string[] ruleSets)
    {
        return ruleSets == null ? Validate(instance) : Validate(new ValidationContext<T>(instance, new PropertyChain(), new RulesetValidatorSelector(ruleSets)));
    }

    public ValidationResult Validate<TValue>(Expression<Func<T, object>> propertyExpression, TValue value)
    {
        return Validate(new T(), propertyExpression, value);
    }

    public ValidationResult Validate<TValue>(T instance, Expression<Func<T, object>> propertyExpression, TValue value)
    {
        MemberExpression memberExpr;
        if (propertyExpression.Body is MemberExpression)
        {
            memberExpr = propertyExpression.Body as MemberExpression;
        }
        else if (propertyExpression.Body is UnaryExpression)
        {
            var unaryExpr = propertyExpression.Body as UnaryExpression;
            memberExpr = unaryExpr.Operand as MemberExpression;
        }
        else
        {
            throw new ArgumentException();
        }

        if (memberExpr == null) throw new ArgumentException();

        var propertyInfo = memberExpr.Member as PropertyInfo;
        if (propertyInfo == null) throw new ArgumentException();

        propertyInfo.SetValue(instance, value, null);

        return this.Validate(instance, propertyExpression);
    }
}
How could I extend the factory to server out my BaseValidator rather than the Abstract one ? Currently I have two factories - one for the ModelValidatorProvider in global.asax and another for my own BaseValidator that I use in the service layer.

Thanks

New Post: Best/Recommended way to include a ruleset as a subset of another ruleset?

$
0
0
Hi all,

I am currently using Fluentvalidation to validate some ViewModels on our site.

On an insert, certain properties are required, and on an update, those certain properties are still required, with the addition of the ID property of the model in question.
        RuleSet("InsertRules", () =>
        {
            RuleFor(x => x.DoctorLastName)
                .NotEmpty().WithMessage("Last Name must be supplied.");

        });

        RuleSet("UpdateRules", () =>
        {
            RuleFor(x => x.DoctorID)
                .NotEmpty().WithMessage("DoctorID must be supplied.")
                .GreaterThan(0).WithMessage("Invalid DoctorID.");

        });
Is there a way that I could allow my code to specify only the UpdateRules ruleset, and know that the InsertRules ruleset would be triggered as well? Thinking this would be cleaner than specifying "*" in our case , and would make the calling code more explicit as to what it was trying to do.

Appreciate any thoughts on this. Thanks!

New Post: Best/Recommended way to include a ruleset as a subset of another ruleset?

$
0
0
There's not really any way to do exactly what you're after....FluentValidation doesn't support rulesets as subsets of one another. The normal way to do this would just be to specify both for execution. That being said, it's a nice idea - I'll have a think about adding it for a future version.

Jeremy

New Post: Best/Recommended way to include a ruleset as a subset of another ruleset?

$
0
0
Great on both counts. Thanks for the quick response!

If you do implement it as a feature, maybe something in the rule set definition as `Includes(RulesetName)` would make sense. Then when generating the context, it would be able to combine rule sets.

I might take a look to see if I can dig into it myself and come up with something.

Sean

E-"mauled" from my mobile device; please excuse typos and brevity.


New Post: Want to pass parameters to a Validator yet be Efficient

$
0
0
Hi, new to Fluent here...

What is the proper way to pass a parameter (of my choosing) to a validator, (called from an mvc controller action) and have the validation act on that parameter? This parameter can be different on every use of the validator.

I know I can pass a parameter to the validator constructor, but then I'd have to instantiate a new validator on every controller request, no? (How efficient/inefficient is that?)

Is it better to do it with an IoC solution passing around a single validator? What is the proper way to do it this way? Also, if I were to do this, is there any chance of concurrent requests clobbering each other?

New Post: Want to pass parameters to a Validator yet be Efficient

$
0
0
Hi

I think it depends on the scenario and what you're trying to achieve.

If your validator needs to make use of some sort of service object to perform validation, then I would tend to inject this through the constructor using an IoC container. Once instantiated, a validator is thread-safe and makes no side-effects, so you can have a single validator, but you'd need to ensure that any dependencies are thread-safe too.

If the parameter that you need to pass is specific to a particular validation request, then you can either:
  • pass it in as a property of the object being validated
  • pass it in via the constructor, but you'd need to instantiate a new validator every time. There is a performance hit for doing this (because of the expression tree compilation), but I wouldn't really worry about this - there are typically much slower things in an application (such as db requests) which are far more noticeable. If you think this might be an issue, then I'd suggest running some profiling tools.
Jeremy

New Post: Can't seem to find the correct syntax for RuleSets in VB.NET

$
0
0
There is no overload when I want to use ruleSet once calling validator.Validate, how i can overcome this issue in VB.NET?

This line is not building: validator.Validate(New Person(), ruleSet:="MyRuleset")

Thanks in advance,
Taiseer

New Post: Can't seem to find the correct syntax for RuleSets in VB.NET

$
0
0
This is an extension method. Ensure you've got the FluentValidation namespace imported.

New Post: Can't seem to find the correct syntax for RuleSets in VB.NET

Commented Issue: Doesn't hook up to MVC ApiControllers [7116]

$
0
0
Hi,

I'm trying to use fluent validation for my MVC 4 WebApi project.
But it only seems to work on controllers that are inherited from the Controller type.

When I use MyController : Controller -> works fine (ModelState.IsValid returns False)
but when I use MyController :ApiController ... nothing.

How can I make this work on the WebApi ?
Comments: Jeremy, I'm not sure you if you are monitoring another [discussion about web api support here](http://fluentvalidation.codeplex.com/SourceControl/network/forks/paulduran/webapisupportv2/contribution/3940), but if you don't - please take a look.

New Post: Checking for Immutable property changes

$
0
0
Hi Jeremy and all,

I am stuck on a particular problem. I am using Fluent Validation to validate my entities before they hit the database and passing the ObjectStateEntry in to check the current state etc and have rule logic.

I have some properties that are immutable and even though i'll try and prevent my View models etc from being able to modify these properties, I need a domain level check to be sure. All I need is to be able to get the property name as a string within a Must validation. I tried "{Property Name}" like I have done in some Custom Error Messages but it doesn't seem to resolve with this.

Is there an override I could use to implement this?

Thanks, Pete
public class SomeClassValidator : AbstractValidator<SomeClass>
{
      public SomeClassValidator(ObjectStateEntry entry)
      {
             switch(entry.State)
             {
                   case EntityState.Added: // Some Checks etc
                           break;
                   case EntityState.Modified:
                             var currentValues = entry.CurrentValues;
                             var originalValues = entry.OriginalValues;

                           RuleFor(p => p.ImmutablePropertyX).Must(x => !HasBeenIllegallyModified("{Property Name}", currentValues, originalValues);
                           RuleFor(p => p.ImmutablePropertyY).Must(y => !HasBeenIllegallyModified({Property Name}, currentValues, originalValues);
                           break;
             }
      }
}

New Post: Checking for Immutable property changes

$
0
0
Hi

The {PropertyName} placeholder is only for use within cuustom messages - you can't access this within a Must rule. You would need to write a custom property validator if you need access to the name of the property within a custom rule.

Jeremy
Viewing all 1917 articles
Browse latest View live


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