-
Notifications
You must be signed in to change notification settings - Fork 68
Validation Rules
When a service command method that accepts parameters (ids or DTOs) is invoked, those parameters are subjected to validation rules. 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.
Here's a sample DTO with validation attributes applied:
using System.ComponentModel.DataAnnotations;
public class Customer : Peasy.Core.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 an InsertCommand (link) or UpdateCommand (link) via a service (link) 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 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 : Peasy.Core.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 (link) or UpdateCommand (link) via a service (link) will pass validation only if Customer.Name and Customer.Age and Customer.BirthDate are set with non-empty string, non-zero, and non-default date values, respectively.