Skip to content
Aaron Hanusa edited this page Feb 6, 2021 · 31 revisions

When a service command method accepting parameters (ids or DTOs) is invoked, those parameters are subjected to validation via the command execution pipeline. Validation rules are generally considered to be general rules about the data itself, such as field required rules, field length rules, etc.

Peasy supports easy validation integrity checks by applying your DTO properties with validation attributes. You can apply your properties with any of the validation rules exposed in the System.ComponentModel.DataAnnotations assembly, or create your own validation attributes, as long as they inherit from System.ComponentModel.DataAnnotations.ValidationAttribute.

More information on creating custom validation attributes can be found here.

Also, be sure to check out business rules if you aren't into data annotations.

Here's a sample DTO with validation attributes applied:

using System.ComponentModel.DataAnnotations;
   
public class Customer : IDomainObject<int>
{
    public int ID { get; set; }
    [Required]
    [StringLength(20)]
    public string Name { get; set; }
    [Required]
    public int Age { get; set; }
    public string City { get; set; }
}

In this example, any Customer DTO passed to the InsertCommand or UpdateCommand methods of a service class will pass validation only if the value for Customer.Name is supplied and the length is less than or equal to 20 characters.

Unfortunately in the above example, not supplying Name with a value will still allow validation to pass, even though it is applied with the Required attribute.

This is due to a limitation of the Required Attribute itself. Validation will also pass when the Required attribute is applied to non-generic numeric properties (Int, Decimal, etc.) and DateTime properties whose values are not set.

To address this limitation, Peasy offers the PeasyRequiredAttribute.

Peasy Validation Attributes

Peasy offers the PeasyRequiredAttribute which when applied to string, DateTime, and non-generic numeric properties (Int, Decimal, etc.), validation will fail when these values are not set.

Here's an example:

public class Customer : IDomainObject<int>
{
    public int ID { get; set; }
    [PeasyRequired]
    public string Name { get; set; }
    [PeasyRequired]
    public int Age { get; set; }
    [PeasyRequired]
    public DateTime BirthDate { get; set; }
}

In this example, any Customer DTO passed to an InsertCommand or UpdateCommand method of a service class will pass validation only if Customer.Name, Customer.Age, and Customer.BirthDate are set with non-empty string, non-zero, and non-default date values, respectively.