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

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: I'll try to go through the source code this week because I do think this is a FluentValidation issue. The Display attribute is used for the source ('Nieuw wachtwoord bevestigen' is a resource string), but not for the target ('NewPassword' is the field name). Of course I could be entirely wrong :)

Reviewed: 3.4 (مارس 05, 2013)

$
0
0
Rated 5 Stars (out of 5) - This is what validation means!

New Comment on "CreatingAValidator"

$
0
0
I don't see the .ValidateAndThrow() method, I'm using FluentValidation.dll version 3.4.6.0. Could you fix it?

New Post: Validating object before adding to nested collection

$
0
0
So FluentValidation is designed to work on validating pre-populated object models, where all the properties have been set and all nested child collections have been fully initialized prior to validation occurring (such as when using a view-model). If you need validation to occur before the item is added to the collection, and you don't want the collection to ever exist in an invalid state, then FluentValidation isn't really appropriate for this, and your existing approach is recommended.

Jeremy

New Post: FluentValidation and Nuget Package BeginCollectionItem

$
0
0
Hello Jeremy,

Is there a workaround for validating collections that using GUID indices like BeginCollectionItem does? FluentValidation validates the collection of models but it returns the wrong property name, i.e. Model[0] instead of Model[GUID].

Thanks...

New Post: FluentValidation and Nuget Package BeginCollectionItem

$
0
0
Hi

I'm afraid not currently - FluentValidation only supports sequential numerical indices in child collections.

Jeremy

New Comment on "CreatingAValidator"

$
0
0
Please do not post comments on these wiki pages - they are not monitored. If you have a question, please open a discussion on the Discussions page.

Created Issue: Validating dynamic attributes [7127]

$
0
0
hi,
awesome library, but could you tell me please how to validate the following
```
public class Product
{
public string Id { get; set; }
public List<Attribute> Attributes { get; set; }
}

public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
}
var person = new Person();
person.Attributes.Add("price","10");

```
how can i validate that price attribute is no more than 5 for example.

thanks in advanced.


New Post: Serializing a validator

$
0
0
Hi,

I am trying to come up with a way to allow users to customize validation (some kind of rules engine idea ...). I wanted to use FluentValidation but I need to be able to serialize and deserialize a FluentValidation validator really (preferably to json). This does not seem to be possible out of the box, but I was wandering if any one had worked on anything similar or knew of a trick in the API to achieve this.

Thanks,

Julian.

Source code checked in, #17238541ccb7

$
0
0
Include memberaccessor and CollectionPropertyRule in SL project

Updated Wiki: CreatingAValidator

$
0
0

Creating a Validator class

Before creating any validators, you will need to add a reference to FluentValidation.dll

To define a set of validation rules for a particular object, you will need to create a class that inherits from AbstractValidator<T>, where T is the type of class that you wish to validate.

For example, imagine that you have a Customer class:

public class Customer {
  public int Id { get; set; }
  public string Surname { get; set; }
  public string Forename { get; set; }
  public decimal Discount { get; set; }
  public string Address { get; set; }
}


You would define a set of validation rules for this class by inheriting from AbstractValidator<Customer>:

using FluentValidation; 

public class CustomerValidator : AbstractValidator<Customer> {
}


The validation rules themselves should be defined in the validator class's constructor. To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression for the property that you wish to validate. For example, to ensure that the Surname property is not null, the validator class would look like this:

using FluentValidation;

public class CustomerValidator : AbstractValidator<Customer> {
  public CustomerValidator {
    RuleFor(customer => customer.Surname).NotNull();
  }
}


Chaining Validators for the Same Property

You can chain multiple validators together for the same property:

using FluentValidation;

public class CustomerValidator : AbstractValidator<Customer> {
  public CustomerValidator {
    RuleFor(customer => customer.Surname).NotNull().NotEqual("foo");
  }
}


This would ensure that the surname is not null and is not equal to the string 'foo'.

To execute the validator, create an instance of the validator class and pass the object that you wish to validate to the Validate method.

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();

ValidationResult results = validator.Validate(customer);


ValidationResult

The Validate method returns a ValidationResult object. This contains two properties:
  • IsValid - a boolean that says whether the validation suceeded.
  • Errors - a collection of ValidationFailure objects containing details about any validation failures.

The following code would write any validation failures to the console:

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();

ValidationResult results = validator.Validate(customer);

if(! results.IsValid) {
  foreach(var failure in results.Errors) {
    Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
  }
}


Throwing Exceptions

Instead of returning a ValidationResult, you can alternatively tell FluentValidation to throw an exception if validation fails by using the ValidateAndthrow method:

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();

validator.ValidateAndThrow(customer);


This throws a ValidationException which contains the error messages in the Errors property.

Note ValidateAndThrow is an extension method, so you must have the FluentValidation namespace imported for this method to be available.

Re-using Validators for Complex Properties

Validators can be re-used for complex properties. For example, imagine you have two classes, Customer and Address:

public class Customer {
  public string Name { get; set; }
  public Address Address { get; set; }
}

public class Address {
  public string Line1 { get; set; }
  public string Line2 { get; set; }
  public string Town { get; set; }
  public string County { get; set; }
  public string Postcode { get; set; }
}


... and you define an AddressValidator:

public class AddressValidator : AbstractValidator<Address> {
  public AddressValidator() {
    RuleFor(address => address.Postcode).NotNull();
    //etc
  }
}


... you can then re-use the AddressValidator in the CustomerValidator definition:

public class CustomerValidator : AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(customer => customer.Name).NotNull();
    RuleFor(customer => customer.Address).SetValidator(new AddressValidator())
  }
} 


... so when you call Validate on the CustomerValidator it will run through the validators defined in both the CustomerValidator and the AddressValidator and combine the results into a single ValidationResult.

Re-using Validators for Collections

Validators can also be re-used on properties that contain collections of other objects. For example, imagine a Customer object that has a collection of Orders:

public class Customer {
   public IList<Order> Orders { get; set; }
}

public class Order {
  public string ProductName { get; set; }
  public decimal? Cost { get; set; }
}

var customer = new Customer();
customer.Orders = new List<Order> {
  new Order { ProductName = "Foo" },
  new Order { Cost = 5 } 
};



... and you've already defined an OrderValidator:

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


....this validator can be used within the CustomerValidator definition:

public class CustomerValidator : AbstractValidator<Customer> {
    public CustomerValidator() {
        RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator());
    }
}

var validator = new CustomerValidator();
var results = validator.Validate(customer);


When the validator is executed, the error messages will reflect the placement of the order object within the collection:

foreach(var result in results.Errors) {
   Console.WriteLine("Property name: " + result.PropertyName);
   Console.WriteLine("Error: " + result.ErrorMessage);
   Console.WriteLine("");
}

Property name: Orders[0].Cost
Error: 'Cost' must be greater than '0'.

Property name: Orders[1].ProductName
Error: 'Product Name' must not be empty.


You can optionally include or exclude certain items in the collection from being validated by using the Where method:

 RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator())
        .Where(x => x.Cost != null);


Rule Sets

RuleSets allow you to group validation rules together which can be executed together as a group whilst ignoring other rules:

For example, let’s imagine we have 3 properties on a Person object (Id, Surname and Forename) and have a validation rule for each. We could group the Surname and Forename rules together in a “Names” RuleSet:

 public class PersonValidator : AbstractValidator<Person> {
  public PersonValidator() {
     RuleSet("Names", () => {
        RuleFor(x => x.Surname).NotNull();
        RuleFor(x => x.Forename).NotNull();
     });
 
     RuleFor(x => x.Id).NotEqual(0);
  }
}


Here the two rules on Surname and Forename are grouped together in a “Names” RuleSet. We can invoke only these rules by passing a ruleSet parameter to the Validate extension method (note that this must be a named parameter as this overload has several options available).

 var validator = new PersonValidator();
var person = new Person();
var result = validator.Validate(person, ruleSet: "Names");


This allows you to break down a complex validator definition into smaller segments that can be executed in isolation.

New Post: Serializing a validator

$
0
0
Hi Julian

I'm afraid this isn't something that FluentValidation supports.

Jeremy

Commented Issue: Validating dynamic attributes [7127]

$
0
0
hi,
awesome library, but could you tell me please how to validate the following
```
public class Product
{
public string Id { get; set; }
public List<Attribute> Attributes { get; set; }
}

public class Attribute
{
public string Name { get; set; }
public string Value { get; set; }
}
var person = new Person();
person.Attributes.Add("price","10");

```
how can i validate that price attribute is no more than 5 for example.

thanks in advanced.

Comments: You could define a custom rule against the Attributes property using a Must validator: ``` public class ProductValidator : AbstractValidator<Product> { public ProductValidator() { RuleFor(x => x.Attributes).Must(HaveValidPrice); } bool HaveValidPrice(List<Attribute> attributes) { var priceAttribute = attributes.Single(x => x.Name == "price"); return int.Parse(priceAttribute.Value) <= 5; } } ```

New Post: Pre Validating Property in class

$
0
0
All my classes are pre validating properties before making changes to ensure all object properties are always in valid state. Validator instance is injected via constructor. My property looks something like this
private string _Name;
public string Name {
    get { return _Name; }
    set {
        if (!Equals(_Name, value) && IsValid(x => x.Name)) {
            _Name = value;
            OnPropertyChanged(x => x.Name);
        }
    }
}
Now, since fluent validation is always validating property value, not new value-to-be, I've changed it to something like this
private string _Name;
public string Name {
    get { return _Name; }
    set {
        if (!Equals(_Name, value)) {
            string _oldValue = _Name;
            _Name = value;
            if (IsValid(x => x.Name)) {
                OnPropertyChanged(x => x.Name);
            } else {
                _Name = oldValue;
            }
        }
    }
}
but every inch of my body is telling me that this is not the way to do it.
Am i missing something? Is there any way I can specify value to be validated (validate "value" instead of "_Name")?

Commented Issue: ValidationFailure constructors cause System.Security.VerificationException in unit tests being run with code coverage [7096]

$
0
0
When running any unit test under a code coverage tool (e.g. TestDriven.NET "Test With" NCover or VS Coverage) which contains a call to either of the ValidationResult constructors, I get a System.Security.VerificationException like

Test 'xxx' failed: System.Security.VerificationException : Operation could destabilize the runtime. at FluentValidation.Results.ValidationResult..ctor()

Based on this SO answer: http://stackoverflow.com/a/2883384/236255, it looks like removing the AllowPartiallyTrustedCallers assembly attribute might be the fix in http://fluentvalidation.codeplex.com/SourceControl/changeset/view/58a381d61018#src%2fCommonAssemblyInfo.cs

Thanks.
Comments: You should remove this line ``` [assembly: AllowPartiallyTrustedCallers] ``` from CommonAssemblyInfo.cs to prevent this error.

Created Issue: NuGet FluentValidation.Mvc does not have a stong name [7128]

$
0
0
I am unable to sign my project because FluentValidation.Mvc doesn't have a strong name. You should sign the libraries you publish on NuGet like everyone else otherwise they can't be used in projects with signed assemblies.

Commented Issue: NuGet FluentValidation.Mvc does not have a stong name [7128]

$
0
0
I am unable to sign my project because FluentValidation.Mvc doesn't have a strong name. You should sign the libraries you publish on NuGet like everyone else otherwise they can't be used in projects with signed assemblies.
Comments: Issue search didn't show any of the previous strong name issues but Google did. Sorry for duplicate.

Commented Issue: NuGet FluentValidation.Mvc does not have a stong name [7128]

$
0
0
I am unable to sign my project because FluentValidation.Mvc doesn't have a strong name. You should sign the libraries you publish on NuGet like everyone else otherwise they can't be used in projects with signed assemblies.
Comments: You should just get rid of the separate signed ones and sign the regular FluentValidation package. The unsigned packages serve no purpose.

Commented Issue: NuGet FluentValidation.Mvc does not have a stong name [7128]

$
0
0
I am unable to sign my project because FluentValidation.Mvc doesn't have a strong name. You should sign the libraries you publish on NuGet like everyone else otherwise they can't be used in projects with signed assemblies.
Comments: No, the unsigned packages will not be removed. Strong-naming adds additional complexities when it comes to versioning, so this should be something you only opt into if you have a good reason for it. The unsigned will remain the default.

Closed Issue: NuGet FluentValidation.Mvc does not have a stong name [7128]

$
0
0
I am unable to sign my project because FluentValidation.Mvc doesn't have a strong name. You should sign the libraries you publish on NuGet like everyone else otherwise they can't be used in projects with signed assemblies.
Viewing all 1917 articles
Browse latest View live


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