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

New Post: field-validation-valid appearing when field-validation-valid expected

$
0
0
I have found a workaround. I have modified my validator class:
        RuleFor(g => g.GraffitiOffensive.SelectedValue.ToString())
            .NotEqual(YesNoType.NotSpecified.ToString())
            .WithName("GraffitiOffensive")
            .WithMessage("Please indicate whether or not the graffiti is ofensive");
I don't think my radio button control class playing happily with Fluent Validation. This works and it's not really a hack, so I'm happy.

Mark

New Post: Multiple When conditions cause unexpected behaviour

$
0
0
A validator I've written with multiple When conditions is not behaving as expected.

Here's the class and the validator:
    class MyClass
    {
        public string Username { get; set; }
    }

    class MyValidator : AbstractValidator<MyClass>
    {
        public MyValidator()
        {
            RuleFor(m => m.Username)
                .Must((model, property) => false).WithMessage("a")
                .When(x => true)
                .Must((model, property) => false).WithMessage("b")
                .When(x => false);
        }
    }
Here's some test code
            MyValidator validator = new MyValidator();
            MyClass m = new MyClass() { Username = "" };
            var x = validator.Validate(m);
            Console.WriteLine(x.Errors.Count);
            foreach (var y in x.Errors)
            {
                Console.WriteLine(y.ErrorMessage);
            }
My understanding is that each When() clause applies to the preceding condition. So you would expect the first condition to be validated (and fail) and the second should not be validated. This would result in "1, a" being output.

But in fact there are no validation errors and the output is "0". The first condition is not validated at all. Am I missing something?

Note that this is almost a duplicate of an earlier discussion (https://fluentvalidation.codeplex.com/discussions/248282), except I've swapped which condition is being validated. It seems to work the other way round.

New Post: Multiple When conditions cause unexpected behaviour

$
0
0
Hi

The default behaviour of the When method applies the condition to all the preceding rules in the chain. So the first When applies to the first Must call, but the second When applies to both. (Essentially it mimics the behaviour of using an AND condition in an if statement).

If you want the condition to only apply to the preceding rules you have two options:
  • Split into two rules (I'd recommend this approach is it makes rules far more readable)
  • You can use the overload of When that takes an ApplyConditionTo
.When(x => true, ApplyConditionTo.CurrentValidator)
Jeremy

New Post: Multiple When conditions cause unexpected behaviour

$
0
0
Thanks very much, that explains it.

I'll go with option 2 I think, because I'd like to stop executing rules once any validation fails. As far as I can tell CascadeMode.StopOnFirstFailure only applies to the current rule. Is there a validator-wide version of this?

New Post: Multiple When conditions cause unexpected behaviour

$
0
0
Yep, there's both a validator-wide option (set the CascadeMode property in the validator's constructor) or a global option (set ValidatorOptions.CascadeMode from within your app's start-up routine)

New Post: Multiple When conditions cause unexpected behaviour

New Post: Validating a list inside a list

$
0
0
I am updating an old validator which does not use FluentValidation to use FluentValidation.

I have a two classes CsvRow which is a List<string> and CsvFile which is a List<CsvRow>

I have a CsvRowValidator
    /// <summary>
    /// Validates a csv file's row.
    /// </summary>
    public class CsvRowValidator : AbstractValidator<CsvRow>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvRowValidator"/> class.
        /// </summary>
        /// <param name="expectedNumberOfRows">The expected number of rows.</param>
        /// <exception cref="System.ArgumentException">The number of expected rows must be greater than or equal to zero.</exception>
        public CsvRowValidator(int expectedNumberOfRows)
        {
            if (expectedNumberOfRows < 0)
                throw new ArgumentException("The number of expected rows must be greater than or equal to zero.");

            RuleFor(row => row.Count).Equal(expectedNumberOfRows);
        }
    }
I want a CsvFileValidator
    public class CsvFileValidator : AbstractValidator<CsvFile>
    {
        public CsvFileValidator(int expectedNumberOfRows)
        {
            if (expectedNumberOfRows < 0)
                throw new ArgumentException("The number of expected rows must be greater than or equal to zero.");


        }
    }
I want this validator to generate an error message for each row in the file:
"Row 23 has 5 columns but expected 6. Knowing which row I'm on is the part I'm having trouble determining. My old validator worked like this:
        public bool Validate(CsvFile file)
        {
            bool valid = true;
            bool validRow;

            _errors.Clear();
            
            int index = 0;
            file.ForEach(row => {
                index++;

                validRow = row.Count == _expectedNumberOfColumns;

                valid &= validRow;

                if (!validRow)
                    _errors.Add(string.Format(ESNCommonTypesResources.RowErrorMessageForFile, index.ToString(), row.Count.ToString(), _expectedNumberOfColumns.ToString()));
            });

            return valid;
        }
Can someone point me in the right direction?

New Post: Is there any CustomizeValidatorAttribute for Web Api

$
0
0
Is fluent web api will support MVC CustomizeValidatorAttribute?

Is there any solution to execute the rulessets/custom binder with web api actions...

New Post: Is there any CustomizeValidatorAttribute for Web Api

$
0
0
No, there's no equivalent of the CustomizeValidatorAttribute for WebAPI, and no plans to add one at present.

Jeremy

Commented Unassigned: Change WebApi dependency to Microsoft.AspNet.WebApi.Core [7174]

$
0
0
Currently depends on Microsoft.AspNet.WebApi change to Microsoft.AspNet.WebApi.Core
Comments: Hi Jeremy, Nice to see this up here already. I see in the nuspec file that the dependency has been updated. Any idea when it will go live? I've got all my api code in a host-agnostic class library and do my integration testing by hosting web api in-process, so this would be nice to have.

New Post: Translation for Finish language

$
0
0
Hello,
here are Finish translation of error messages:

email_error '{PropertyName}' ei ole kelvollinen sähköpostiosoite.
equal_error '{PropertyName}' pitäisi olla yhtäsuuri kuin '{ComparisonValue}'.
exact_length_error '{PropertyName}' pitää olla {MaxLength} merkkiä pitkä. Syötit {TotalLength} merkkiä.
exclusivebetween_error '{PropertyName}' pitää olla välillä {From} ja {To} (exclusive). Syötit {Value}.
greaterthan_error '{PropertyName}' pitää olla suurempi kuin '{ComparisonValue}'.
greaterthanorequal_error '{PropertyName}' pitää olla suurempi tai yhtä suuri kuin '{ComparisonValue}'.
inclusivebetween_error '{PropertyName}' pitää olla välillä {From} ja {To}. Syötit {Value}.
length_error '{PropertyName}' pitää olla välillä {MinLength} ja {MaxLength} merkkiä. Syötit {TotalLength} merkkiä.
lessthan_error '{PropertyName}' pitää olla pienempi kuin '{ComparisonValue}'.
lessthanorequal_error '{PropertyName}' pitää olla pienempi tai yhtä suuri kuin '{ComparisonValue}'.
notempty_error '{PropertyName}' ei pitäisi olla tyhjä.
notequal_error '{PropertyName}' ei voi olla yhtäsuuri kuin '{ComparisonValue}'.
notnull_error '{PropertyName}' ei voi olla tyhjä.
predicate_error Määritetty ehto ei toteutunut '{PropertyName}'.
regex_error '{PropertyName}' ei ole oikeassa muodossa.

BR
Mira

New Post: Is there any CustomizeValidatorAttribute for Web Api

$
0
0
Is there any alternative for web Api to execute FluentValidation Ruleset.

Thanks,
Hanu
Sent from Windows Mail

New Post: Is there any CustomizeValidatorAttribute for Web Api

$
0
0
You'd need to manually invoke the validator's Validate method rather than relying on the automatic validation.

Jeremy

New Post: Translation for Finish language

$
0
0
Thanks for this. If you'd like it included in the project, please could you either submit a pull request or attach this as a RESX file to an issue.

Thanks

Jeremy

New Post: PCL nuget packages for 158

$
0
0
Hello,

I want to use this library within a PCL project that targets .NET Framework 4.5 and higher; Silverlight 5; Windows Phone 8; Windows Store apps (Windows 8) and higher; Xamarin.Android; Xamarin.IOS (profile 158).

The problem is that I can't use FluentValidation using Nuget (it doesn't appear) so I have to download the source code and just compile the PCL project and add manually to my project (the Fluent PCL project is compatible with my configuration).

Could anyone modify the nuget packages so it can be used with this configuration?

Thanks

New Post: PCL nuget packages for 158

$
0
0
I have found in Json.net the following lines:
@{Name = "Newtonsoft.Json.Portable"; TestsName = "Newtonsoft.Json.Tests.Portable"; Constants="PORTABLE"; FinalDir="Portable"; NuGetDir = "portable-net45+wp80+win8+wpa81"; Framework="net-4.0"; Sign=$true},
@{Name = "Newtonsoft.Json.Portable40"; TestsName = "Newtonsoft.Json.Tests.Portable40"; Constants="PORTABLE40"; FinalDir="Portable40"; NuGetDir = "portable-net40+sl4+wp7+win8"; Framework="net-4.0"; Sign=$true},
but I don't see where to put in build.ps1 (or even if it's there where they must be).

Created Unassigned: Czech and Finish translations [7175]

$
0
0
Czech and Finish translations resx files attached

New Post: Translation for Finish language

New Post: Translation for Finish language

$
0
0
Thanks for this. I'm away without access to my laptop for the next 2 weeks, so I'll try and get it included when I'm back.

Jeremy

New Post: How to by pass calling the InstanceCache?

$
0
0
Hi,

My situation is. I have a validator trying to make sure the user has not entered a future date. so I have a validator like this.
public class BasedViewModelValidator<T> : AbstractValidator<T> where T : BasedViewModel
    {
        public BasedViewModelValidator()
        {
            RuleFor(x => x.TradeDate).LessThan(DateTime.Now.Date.AddDays(1));
        }
    }
The issue is that the InstanceCache "cached" the validator instance and would render the rule invalid after one day.

How could I work around this issue? or disable the caching altogether?

Thanks,

J.
Viewing all 1917 articles
Browse latest View live


Latest Images

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