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

New Post: Pure inline validation without validation/DTO classes

$
0
0
Thanks for confirming my conclusion!

I fully understand that this is outside the scope. I'll do some experiments in my own fork, without taking into consideration that I'll have to merge it back in :)

Thanks,
Mark

New Post: Validating single rule if the first rule fails.

$
0
0
Jeremy,

I too came to a need to stop before the heavier validations run. I have a few validations on properties which run very fast and then a few validations against my DB which are slow and complex. i want to skip the DB validations if any of the property validations fail.
my first thought after reading this thread was to create two rule sets. Quick validation and Slow validation. run the quick and then the slow one. skip the slow if the quick one failed. that would probably work but it would make the code less elegant.
I took a look on the code and think i have an easy proposal for implementation:
if you could add an extension that would allow me to write
//Quick validations on level 1
RuleFor(r => r.RequiredFields.Count).ForValidationLevel(1).GreaterThan(0).When(x => x.RequiredFields != null);
...
//Slow validations on level 2
RuleFor(r => r.RequiredFields.Count).ForValidationLevel(2).Must(NotHaveDuplicate);
then on your validate method where you do errors=Rules.SelectMany(Rule=>Rule.Validate) (or similar) you could just split the rules into levels, run on each level by order and then run all it's validators. fail in any validators of the current level stops the validation process.

i think it should be fairly easy to implement and would solve a need by many users of this great library

New Post: Best way to apply global/default rules for primitive (string) types

$
0
0
Hi folks,

We're wanting to enforce some global rules for string inputs (basically a regex match to prevent malicious input), and then allow the validators to override it on specific fields if needed. What's the best way to approach this? I've looked at
  • PropertyValidator, but you have to call SetValidator on each field
  • AbstractValidator<string>, but this doesn't seem to get picked up and run
At the moment, I'm thinking we'll have to use a Base class that all our validators inherit from, reflect over the validation type and add our custom validation rules for any public string properties. But I'm hoping there might be a nicer way?

Thanks

J

New Post: Complex Property Validation issues

$
0
0
So I have a model that has a property that is of Type A.

Type A has a value and text.

I'm using this Type A across many different properties on my model.

I have a validator rule such as:

RuleFor(u => u.Something).SetValidator(new ValueValidation());

and in the ValueValidation class that inherits from AbstractValidator<A> I have:

RuleFor(u => u.Value).NotEmpty().WithMessage("blah");

How do I customize my message so I can use it across different fields??

I tried creating a property on ValueValidation class and then setting it such as below:
RuleFor(u => u.Something).SetValidator(new ValueValidation() { Message = "asdfas" });

Then i'm using that message as the parameter for WithMessage.

This ofcourse does not work. Any ideas on how to fix this?

Thanks,
Sunny

New Post: Complex Property Validation issues

$
0
0
Hi Sunny

If you take the Message as a constructor argument for your ValueValidator rather than as a property, then you should be able to use this within the child rule's WithMessage call.

Jeremy

New Post: Best way to apply global/default rules for primitive (string) types

$
0
0
I can't really think of another way to do this without reflecting over all the properties as you suggested. I think this is your best bet for now.

Jeremy

New Post: Best way to apply global/default rules for primitive (string) types

$
0
0
Thanks Jeremy, we ended up deciding this was probably a bad plan anyway - not exactly business validation rules! Was just looking for a nice way to get the AllowHtml/ValidateRequest type behaviour but with validation errors per field ... ended up doing it at the model binder level instead. Thanks again.

New Post: Complex Property Validation issues

$
0
0
I tried this as well before posting and that did not work.

Since I now have a constructor that takes in a message, I have to provide a default constructor or MVC complains. So here's what I have:

UserValidation class:

RuleFor(u => u.Something).SetValidator(new Validation("test"));

ValueValidation class:

public ValueValidation (string message) { RuleFor (u => u.Value).NotEmpty(message); }
public ValueValidation () { RuleFor (u => u.Value).NotEmpty("blah"); }

Regardless of the fact that I set the message in the UserValidation class, it always goes to the default constructor and uses "blah" as my message...

Any reason why this is happening? Or do you have any ideas on how to solve this?

Let me know,
Thanks,
_sunny

New Post: Complex Property Validation issues

$
0
0
Hi

If you're using a child validator as part of a SetValidator call, then you should exclude this from the MVC integration (if you're using FV's Validator attribute, then be sure to remove this from the Value class). Once you've excluded it from the MVC integration, you can remove the default constructor.

Jeremy

New Post: Validating single rule if the first rule fails.

$
0
0
Hi Jeremy,

This shortcoming IMO was the biggest barrier when I did POCs for making the decision of whether or not to use FluentValidation library. I ended up not using it due to this reason. It was a great disappointment as this library has so many things to offer. I do hope you add this functionality where a rule can depend on another rule.

New Post: Validating single rule if the first rule fails.

$
0
0
Well, if someone wants to have a go at adding this then pull requests are always welcome...

New Post: Validating interfaces (for reusability)

$
0
0
is this still the best/only way in FluentMvc4 ? or there's a built-in feature/method for this?

New Post: Rule GreaterThan and WithMesssage

$
0
0
Hi,

I would like to customize error messages for validations using the rule GreaterThan. The property associated with the rule is an id selected from a dropdownlist in an ASP.NET MVC view.
However, the message shown to the user is the default generated by validation engine ("'countryId' must not be null"). Below is the code for the rule:

this.RuleFor(cust => cust.CountryId).GreaterThan(0).WithMessage("Country is required");

Any suggestions?

New Post: Rule GreaterThan and WithMesssage

$
0
0
Hi

It sounds like the GreaterThan rule isn't actually executing.

If the property is a non-nullable value type (such as an int) then MVC will look for and try to invoke a Required rule before it will run any other rules (this is a requirement of MVC, not of FluentValidation). You can get around this by adding a NotNull rule for the CountryId.

New Post: Rule GreaterThan and WithMesssage


Commented Issue: Equal does not use the Display Attribute [7125]

$
0
0
```c#
[Display(Name = "NewPassword", ResourceType = typeof(Labels))]
[DataType(DataType.Password)]
public string NewPassword { get; set; }

[Display(Name = "NewPasswordVerification", ResourceType = typeof(Labels))]
[DataType(DataType.Password)]
public string NewPasswordVerification { get; set; }
```
```c#
RuleFor(m => m.NewPasswordVerification).Equal(m => m.NewPassword);
```

Output:
Nieuw wachtwoord [input field]
Nieuw wachtwoord bevestigen [input field] 'Nieuw wachtwoord bevestigen' moet gelijk zijn aan 'NewPassword'.
Comments: It's been a while,but I finally got back to this. The built-in validation attribute `[Compare("Foo")]` gets localised names for the source and the target of the comparison. I've also found why Fluent Validation does not get a localised name for the target of the comparison. In the `EqualToFluentValidationPropertyValidator` class, lines 26-28: ``` var formatter = new MessageFormatter() .AppendPropertyName(Rule.GetDisplayName()) .AppendArgument("ComparisonValue", propertyToCompare.Name); ``` So for `"ComparisonValue"` there's never an attempt made to get a localised name. I can write up a pull request but it'd probably not be in the right place in the codebase, unless you don't mind?

New Post: Validate total across multiple properties

$
0
0
I have a group of "percentage" properties in my view model. As a simple example:
public class ViewModel
{
     public int Percent1 { get; set; }
     public int Percent2 { get; set; }
     public int Percent3 { get; set; }
     public int Percent4 { get; set; }
}
I need to write a validation rule that ensures the total of these four properties equals 100. From what I've read, fluent validation requires that a rule be applied to an individual property rather than across multiple properties.

Is there an elegant way to do this within the confines of the FluentValidation framework?

New Post: Validate total across multiple properties

$
0
0
Hi

Yes, FluentValidation is designed to associate validation rules with a particular property. I'd suggest creating an additional read-only TotalPercentage property on the model which sums the properties. This also has the advantage of keeping the summation logic within your model, rather than having it leak into the validator.

If you really don't want to do this, then your other option is to use the AbstractValidator.Custom method

Jeremy

New Post: Using SetCollectionValidator - Overriding/Adding RuleSet

$
0
0
I'm trying to reuse a validator within another validator. The subvalidator doesn't have any rulesets defined but the validator using it does. When I call the validator with a ruleset it will not result in no validation errors since it's looking for the ruleset. Is there a way to override this or add the "default" ruleset?

Here's an example of what I'm trying to do.
    public class AuthPlanEntry
    {
        public DateTime? StartDate {get ; set;}
        public DateTime? EndDate { get; set;}
    }

    public class AuthChange
    {
        public AuthChange() { }
        public string Comments { get; set; }
        public List<AuthPlanEntry> AuthPlanEntries { get; set; }
    }

    internal class AuthPlanEntryValidator : AbstractValidator<AuthPlanEntry>
    {
        internal AuthPlanEntryValidator()
        {
            RuleFor(x => x.StartDate)
                .NotNull()
                .GreaterThan(SqlDateTime.MinValue.Value).WithMessage("Invalid Date");

            RuleFor(x => x.EndDate)
                .NotNull()
                .GreaterThan(x => x.StartDate.Value).WithMessage("Invalid Date")
                .When(x => x.EndDate.HasValue && x.StartDate.HasValue);
        }
    }

    public class AuthChangeValidator : AbstractValidator<AuthChange>
    {
        public AuthChangeValidator()
        {
            RuleSet("MyRuleSet", () =>
            {
                RuleFor(x => x.AuthPlanEntries).SetCollectionValidator(new AuthPlanEntryValidator());

                RuleFor(x => x.Comments)
                    .Cascade(CascadeMode.StopOnFirstFailure)
                    .NotEmpty().WithMessage("Comments are required");
            });
        }
    }
If I call validate on an AuthChangeValidator with the ruleset it will pass even if the auth plan entries have invalid dates.

New Post: Using SetCollectionValidator - Overriding/Adding RuleSet

$
0
0
Hi

The default behaviour is to cascade the ruleset selection to child validators. You can bypass this by writing your own implementation of IValidatorSelector rather than using the default RulesetValidatorSelector. Example:
public class MyValidatorSelector : IValidatorSelector {
    RulesetValidatorSelector _inner;
    string[] _ruleSetsToExecute;

    public MyValidatorSelector(string[] ruleSetsToExecute) {
        _inner = new RulesetValidatorSelector(ruleSetsToExecute);
        _ruleSetsToExecute = ruleSetsToExecute;
    }

    public bool CanExecute(IValidationRule rule, string propertyPath, ValidationContext context) {
        // If we're executing a child validator, and the child validator has no ruleset defined, then include it
        if (context.IsChildContext && string.IsNullOrEmpty(rule.RuleSet) && _ruleSetsToExecute.Length > 0) {
            return true;
        }
        return _inner.CanExecute(rule, propertyPath, context);
    }
}
Example usage:
public class MyValidator : AbstractValidator<Person> {
    public MyValidator() {
        RuleSet("test", () => {
            RuleFor(x => x.Surname).NotNull();
            RuleFor(x => x.Orders).SetValidator(new OrderValidator());
        });

        RuleFor(x => x.Forename).NotNull();
    }
}

public class OrderValidator : AbstractValidator<Order> {
    public OrderValidator() {
        RuleFor(x => x.ProductName).NotNull();
    }
}

var person = new Person() {
    Orders = {new Order()}
};

var validator = new MyValidator();

var rulesets = new[] { "test" };
var result = validator.Validate(person, selector: new MyValidatorSelector(rulesets));
Viewing all 1917 articles
Browse latest View live


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