Skip to content

Models validator

AventusSharp allows you to implement custom validators to automatically validate model data before inserting it into the database. These validators can help ensure data integrity and consistency by enforcing specific rules, such as checking the format of an email address or validating a phone number. Validators act as attributes on model properties, enabling seamless integration with the model structure.

The advantage of using validators as attributes is twofold:

  1. Code Clarity: Adding a validation rule directly above a property makes it clear to future developers which constraints apply to that property.
  2. Automated Validation: Validators are executed automatically during data operations, so your model’s integrity is enforced without extra manual checks.

Example: Creating a Custom Validator

In the example below, we’ll create a RandomValidator to demonstrate the use of a custom validator in AventusSharp. This validator randomly succeeds or fails, simulating a validation scenario where certain conditions must be met for the property value to be accepted. In real applications, you might replace this with validators for email, phone numbers, or other fields.

RandomValidator.cs
using System;
using AventusSharp.Data;
using AventusSharp.Data.Attributes;
using AventusSharp.Tools;
namespace Demo.Data.Validators
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class RandomValidator : ValidationAttribute
{
private static readonly Random _random = new Random();
/// <summary>
/// Checks if the current value is valid.
/// </summary>
/// <param name="value">The property value to validate.</param>
/// <param name="context">The validation context.</param>
/// <returns>A ValidationResult indicating success or failure.</returns>
public override ValidationResult IsValid(object? value, ValidationContext context)
{
if (_random.Next(2) == 0)
{
return ValidationResult.Success;
}
// Return a custom error if validation fails
return new ValidationResult()
{
Errors = new List<GenericError>() {
new DemoError(DemoErrorCode.ManualFailed, "You are unlucky") {
Details = new List<object>() { new FieldErrorInfo(context.FieldName) }
}
}
};
// Alternatively, return an error directly with DataError
return new ValidationResult("You are unlucky", context.FieldName);
}
}
}

In this example:

  • The RandomValidator attribute can be applied to fields or properties, as specified by [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)].
  • In the IsValid method, a ValidationResult.Success is returned if the randomly generated condition passes. Otherwise, a ValidationResult containing a custom error message and field details is returned.

Usage :

Once defined, you can apply your custom validator to any model property by adding the attribute above the property declaration. This will automatically invoke the validation before saving or updating the model in the database.

User.cs
using AventusSharp.Data;
using Demo.Data.Validators;
namespace Demo.Data
{
public class User : Storable<User>
{
[RandomValidator]
public string Username { get; set; } = "";
// Other properties...
}
}

By placing [RandomValidator] above the Username property, the RandomValidator logic will be invoked whenever the User model is validated. If the validation fails, an error message is generated based on the custom error logic defined in the validator.

Custom validators allow you to enforce business rules across your application with minimal code repetition, keeping validation logic centralized and improving the overall maintainability of your application.