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

Updated Wiki: Validators

$
0
0

Built in Validators

FluentValidation ships with several built-in validators. The error message for each validator can contain special placeholders that will be filled in when the error message is constructed.

NotNull Validator

Description: Ensures that the specified property is not null.

Example:
RuleFor(customer => customer.Surname).NotNull();

Example error: 'Surname' must not be empty.
String format args:
  • {PropertyName} = The name of the property being validated
  • {PropertyValue} = The current value of the property

NotEmpty Validator

Description: Ensures that the specified property is not null, an empty string or whitespace (or the default value for value types, eg 0 for int)

Example:
RuleFor(customer => customer.Surname).NotEmpty();

Example error: 'Surname' should not be empty.
String format args:
  • {PropertyName} = The name of the property being validated
  • {PropertyValue} = The current value of the property

NotEqual Validator

Description: Ensures that the value of the specified property is not equal to a particular value (or not equal to the value of another property)

Example:
//Not equal to a particular value
RuleFor(customer => customer.Surname).NotEqual("Foo");

//Not equal to another property
RuleFor(customer => customer.Surname).NotEqual(customer => customer.Forename);

Example error: 'Surname' should not be equal to 'Foo'
String format args:
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} = Value that the property should not equal

Equal Validator

Description: Ensures that the value of the specified property is equal to a particular value (or equal to the value of another property)

Example:
//Equal to a particular value
RuleFor(customer => customer.Surname).Equal("Foo");

//Equal to another property
RuleFor(customer => customer.Password).Equal(customer => customer.PasswordConfirmation);

Example error: 'Surname' should be equal to 'Foo'
String format args:
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} = Value that the property should equal
  • {PropertyValue} = The current value of the property

Length Validator

Description: Ensures that the length of a particular string property is within the specified range.

Example:
RuleFor(customer => customer.Surname).Length(1, 250); //must be between 1 and 250 chars (inclusive)

Example error: 'Surname' must be between 1 and 250 characters. You entered 251 characters.
Note: Only valid on string properties.
String format args:
  • {PropertyName} = The name of the property being validated
  • {MinLength} = Minimum length
  • {MaxLength} = Maximum length
  • {TotalLength} = Number of characters entered
  • {PropertyValue} = The current value of the property

Less Than Validator

Description: Ensures that the value of the specified property is less than a particular value (or less than the value of another property)
Example:
//Less than a particular value
RuleFor(customer => customer.CreditLimit).LessThan(100);

//Less than another property
RuleFor(customer => customer.CreditLimit).LessThan(customer => customer.MaxCreditLimit);

Example error: 'Credit Limit' must be less than 100.
Notes: Only valid on types that implement IComparable<T>
String format args:
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} - The value to which the property was compared
  • {PropertyValue} = The current value of the property

Less Than Or Equal Validator

Description: Ensures that the value of the specified property is less than or equal to a particular value (or less than or equal to the value of another property)
Example:
//Less than a particular value
RuleFor(customer => customer.CreditLimit).LessThanOrEqual(100);

//Less than another property
RuleFor(customer => customer.CreditLimit).LessThanOrEqual(customer => customer.MaxCreditLimit);

Example error: 'Credit Limit' must be less than or equal to 100.
Notes: Only valid on types that implement IComparable<T>
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} - The value to which the property was compared
  • {PropertyValue} = The current value of the property

Greater Than Validator

Description: Ensures that the value of the specified property is greater than a particular value (or greater than the value of another property)
Example:
//Greater than a particular value
RuleFor(customer => customer.CreditLimit).GreaterThan(0);

//Greater than another property
RuleFor(customer => customer.CreditLimit).GreaterThan(customer => customer.MinimumCreditLimit);

Example error: 'Credit Limit' must be greater than 0.
Notes: Only valid on types that implement IComparable<T>
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} - The value to which the property was compared
  • {PropertyValue} = The current value of the property

Greater Than Or Equal Validator

Description: Ensures that the value of the specified property is greater than or equal to a particular value (or greater than or equal to the value of another property)
Example:
//Greater than a particular value
RuleFor(customer => customer.CreditLimit).GreaterThanOrEqual(1);

//Greater than another property
RuleFor(customer => customer.CreditLimit).GreaterThanOrEqual(customer => customer.MinimumCreditLimit);

Example error: 'Credit Limit' must be greater than or equal to 1.
Notes: Only valid on types that implement IComparable<T>
  • {PropertyName} = The name of the property being validated
  • {ComparisonValue} - The value to which the property was compared
  • {PropertyValue} = The current value of the property

Predicate Validator (aka Must)

Description: Passes the value of the specified property into a custom delegate that can perform custom validation logic on the value

Example:
RuleFor(customer => customer.Surname).Must(surname => "Foo".Equals(surname));

Example error: The specified condition was not met for 'Surname'
String format args:
  • {PropertyName} = The name of the property being validated
  • {PropertyValue} = The current value of the property

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:

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


(Note that in this particular example, it would be better to use the cross-property version of NotEqual)

Regular Expression Validator

Description: Ensures that the value of the specified property matches the given regular expression.
Example:
RuleFor(customer => customer.Surname).Matches("some regex here");

Example error: 'Surname' is not in the correct format.
String format args:
  • {PropertyName} = The name of the property being validated
  • {PropertyValue} = The current value of the property

Email Validator

Description: Ensures that the value of the specified property is a valid email address format.
Example:
RuleFor(customer => customer.Email).EmailAddress();

Example error: 'Email' is not a valid email address.
String format args:
  • {PropertyName} = The name of the property being validated
  • {PropertyValue} = The current value of the property
The regular expression used by the email validator can be found at http://regexlib.com/REDetails.aspx?regexp_id=1448

Commented Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basicly I want to be able to have a ruleset which specifies the length not to be 1 to 140but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


Comments: Yes thank you. However my problem still remains, since the replacerule gets executed in the constructor instead of at validation time when the ruleset is used.

Commented Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basicly I want to be able to have a ruleset which specifies the length not to be 1 to 140but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


Comments: Yes, so this is the correct behaviour - validator definitions are all built once when the validator is instantiated - you can't embed something like RemoveRule inside the validator's constructor as it will fire immediately as soon as the validator is instantiated. RemoveRule is used for a one-off modification of the rules after the validator has been instantiated. In your situation, it'd be better to define the rule twice in different rulesets rather than trying to use RemoveRule for this. Jeremy

New Post: How to associate a rule with more than one property

$
0
0
Hi Jeremy,

Thanks for the great framework!

One question, how do you associate a validation rule with more than one property for complex form level validation. The same kind of thing that you get with IValidatableObject.Validate().

Ryan

New Post: How to associate a rule with more than one property

$
0
0
Hi Ryan

Many of the built-in validators in FluentValidation can work with multiple properties. For example, if you wanted to check that Property1 is not equal to Property2 you could do this:
RuleFor(x => x.Property1).NotEqual(x => x.Property2)
Here the rule uses multiple properties, but the error message is associated with Property1.

Similarily, you can use the Must validator to access all of the properties in the object being validated:
public CustomerValidator() {
  RuleFor(x => x.UserName).Must(NotEqualFirstAndLastName)
}

private bool NotEqualFirstAndLastName(Customer customer, string username) {
  return username != customer.Surname && username != customer.LastName;
} 
Jeremy

New Post: How to associate a rule with more than one property

$
0
0
Wow, thanks for the quick reply!

That's not the scenario that I'm trying to solve. My scenario is where you have two properties that are not valid. For example, say you need to validate that Password and ConfirmPassword properties are equal. In the IValidatableObject model you would return a ValidationResult like below

return new ValidationResult("Password and Confirm Password must match.", new List<string>{ "UserName", "Password"});

this will allow the client (like MVC) to be able to know which properties are involved in the complex validation failure.

Is this supported or possible?

-Ryan

New Post: How to associate a rule with more than one property

$
0
0
Ah, I see what you mean.

No, this isn't supported with FluentValidation I'm afraid - you always have to choose a single property to be the target of your RuleFor declaration, and this is the property that will end up with the error associated with it. With something like Password/ConfirmPassword, I'd tend to associate the error with the Password property, but I appreciate this may not be ideal in all scenarios. I'll have a think about how practical this would be to add in a future version.

Jeremy

New Post: How to associate a rule with more than one property

$
0
0
It's useful in frameworks like MVC that will highlight all the properties for you if you use IValidatableObject. I'm working on a solution for this on my end that uses a combination of Extension Methods and a ConditionalWeakTable to make it easy to add IValidatableObject support using your fluent framework. If your interested in what I come up with let me know and I can let you review it when I'm done.

Commented Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basicly I want to be able to have a ruleset which specifies the length not to be 1 to 140but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


Comments: That would mean I would get two validation errors when I have an input string where it's length would be <70, while only the latest rule should be applied and the other one be ignored. Even though RemoveRule is used for a one-off modification, is there no other way to accomplice what I want to achieve?

Commented Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basicly I want to be able to have a ruleset which specifies the length not to be 1 to 140but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


Comments: You wouldn't get two rules executed if you include them in separate rulesets, then explicitly choose which one you want to execute. See the documentation on named rulesets: https://fluentvalidation.codeplex.com/wikipage?title=CreatingAValidator&referringTitle=Documentation&ANCHOR#RuleSets

Commented Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basicly I want to be able to have a ruleset which specifies the length not to be 1 to 140but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


Comments: Even though it isn't exactly what I was hoping for, it will be enough to solve my problem. Thank you for providing me with a solution.

Edited Unassigned: ValidatorType Replace- RemoveRule [7143]

$
0
0
What type is the following validator:

RuleFor(x => x.Surname).Length(1, 140).Unless(MyUnlessMethod);

The Replace/RemoveRule methods needs a type, but when I supply it with typeof(LengthValidator) it doesn't work.

Basically I want to be able to have a ruleset which specifies the length not to be 1 to 140 but 1 to 70.
But in both cases and I need to be able to ignore the rule when the Unless case is met.


New Post: How to Check the validation for the Combo box with Enum in mvc razor

$
0
0
Hi Experts,

In my Model there is a Property Genders as Selectlist that value i am assigning in selectedgenderid which is int.


@Html.DropDownListFor(modelItem => Model.SelectedGenderid, Model.Genders)


then i need to check the validation for the SelectedGenderid .

RuleFor(x => x.SelectedGenderid).NotNull().WithLocalizedMessage(() => ValidationMessage.TRAVELERTITLENOTNULL);

New Post: How to associate a rule with more than one property

$
0
0
Yes, please feel free to post your solution.

Created Unassigned: How to validate the condition on dropdownloistfor in mvc razor [7144]

$
0
0
hi everybody,

int genderid;
selectlist genders;

html.dropdownlistfor ( genderid ,genders);


these are my three values in my drop down that i am unable to validate with fluent validation.

0 select
1 male
2 female



so can you please suggest me how to handle it.

Commented Unassigned: How to validate the condition on dropdownloistfor in mvc razor [7144]

$
0
0
hi everybody,

int genderid;
selectlist genders;

html.dropdownlistfor ( genderid ,genders);


these are my three values in my drop down that i am unable to validate with fluent validation.

0 select
1 male
2 female



so can you please suggest me how to handle it.
Comments: Please could you provide more information - I'm going to need more than that to go on if you'd like me to help. What do you mean when you say that the values are "unable to validate"? Are you getting an error? How have you defined your validator?

New Post: Best way to override default validator messages?

$
0
0
In a project I work, we have some custom messages for standard validators like "notempty" or "length".

Today, we change them with "WithMessage".

The problem is that we have a standard error message for "NotEmpty", its just different then what comes with the package, so today all of our validation must have a WithMessage in all validations pointing to the same variable, which makes the code quite ugly.

Is there any better way to handle this that is not change FluentValidation source and recompile ? The ideal thing would be to somehow say in my project "the default message for NotEmpty now is this: ..." and just use the .NotEmpty();

New Post: Best way to override default validator messages?

$
0
0
Hi

You can override FluentValidation's default error messages by replacing the default resource provider. See the section on "using a custom resource provider type" at the bottom of this page: https://fluentvalidation.codeplex.com/wikipage?title=Localization&referringTitle=Documentation

Essentially, you need to create a resource file to include your new error messages and then tell FluentValidation to use this file by setting ValidatorOptions.ResourceProviderType to your resource provider type.

Jeremy

New Post: Best way to override default validator messages?

$
0
0
Thanks, that is exactly what I was looking for!

I didn't think about localization. Maybe its a good idea to add a link to that page from the "Overriding the Default Error Message" page in the wiki saying "if you want to override all default messages, click here" or something like that.

New Post: Best way to override default validator messages?

$
0
0
Good idea - I'll get that changed.
Viewing all 1917 articles
Browse latest View live