‹ 首页

abp-validation

@burakdmir · 收录于 昨天 · 上游提交 2 周前

ABP Framework v10.x (10.4/10.5) validation: DTO validation, Data Annotations, FluentValidation, IValidatableObject, AbpValidationException. Use when you need input validation or DTO validation in ABP.

适合你,如果正在用 ABP 框架开发,需要为 DTO 添加验证规则。

/ 通过 npx 安装 校验哈希
npx oh-my-skill add burakdmir/abp-skills/abp-validation
/ 通过 bash 安装
curl -fsSL https://oh-my-skill.com/install.sh | bash -s -- burakdmir/abp-skills/abp-validation
/ 已经装过?验证本机副本,不用重装
npx oh-my-skill verify burakdmir/abp-skills/abp-validation
安装目标可用 --agent / --scope 或 --to 明确指定;省略时只会在唯一已存在的 agent 目录上自动选择,零命中或多命中会停止并提示。content_hash 缺失或不一致均拒装。
13GitHub stars
~1.2K上下文体积 · 单文件
索引托管

怎么用

商店整理自技能原文 · 版本 ce71259 · 表述以原文为准
它做什么

当用户询问ABP Framework的输入验证时,Claude会提供Data Annotations、FluentValidation、IValidatableObject、IValidationEnabled的使用示例,并解释验证异常处理流程和最佳实践。

什么时候触发

当用户提到“DTO验证”、“FluentValidation”、“IValidatableObject”、“AbpValidationException”或“ABP输入验证”等关键词时触发。

装好后可以这样说
Claude会给出Data Annotations示例。
Claude会展示安装和配置步骤。
Claude会介绍IValidationEnabled接口。
技能原文 SKILL.md作者撰写 · MIT · ce71259

ABP Validation Skill

Trigger

User asks about validation, DTO validation, FluentValidation, IValidatableObject, validation errors, AbpValidationException, or input validation in ABP Framework.


Core Concepts

ABP provides automatic validation for application service inputs using:

  1. Data Annotation Attributes — Declarative validation on DTOs
  2. IValidatableObject — Custom validation logic in DTOs
  3. FluentValidation — External validator classes
  4. IValidationEnabled — Enable validation on any DI-registered service

Validation errors are automatically caught and returned as standardized error responses.


Data Annotation Validation
Basic Usage
public class CreateBookDto
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Required]
    [StringLength(1000)]
    public string Description { get; set; }

    [Range(0, 999.99)]
    public decimal Price { get; set; }
}
  • Automatically validated when used as application service/controller parameter
  • Localized validation exception thrown and handled by ABP
  • Common attributes: Required, StringLength, Range, EmailAddress, RegularExpression, MinLength, MaxLength

IValidatableObject
Custom Validation in DTOs
public class CreateBookDto : IValidatableObject
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        if (Price <= 0)
        {
            results.Add(new ValidationResult(
                "Price must be greater than zero.",
                new[] { nameof(Price) }
            ));
        }

        if (string.IsNullOrWhiteSpace(Name))
        {
            results.Add(new ValidationResult(
                "Name cannot be empty.",
                new[] { nameof(Name) }
            ));
        }

        return results;
    }
}
Resolving Services in Validate
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var myService = validationContext.GetRequiredService<IMyService>();
    // Use service for validation logic
    // ...
}
Warning: Resolving services in Validate is possible but not recommended. Keep DTOs simple — they should transfer data, not contain domain validation logic.

FluentValidation Integration
Installation
abp add-package Volo.Abp.FluentValidation

Or manually:

dotnet add package Volo.Abp.FluentValidation

Add module dependency:

[DependsOn(typeof(AbpFluentValidationModule))]
public class MyModule : AbpModule { }
Usage
public class CreateUpdateBookDtoValidator : AbstractValidator<CreateUpdateBookDto>
{
    public CreateUpdateBookDtoValidator()
    {
        RuleFor(x => x.Name).Length(3, 10);
        RuleFor(x => x.Price).ExclusiveBetween(0.0f, 999.0f);
        RuleFor(x => x.Description).NotEmpty().MaximumLength(1000);
    }
}
  • ABP auto-discovers validator classes
  • Automatically associated with the DTO type
  • Can be placed in the same project as the DTO

Validation Infrastructure
IValidationEnabled Interface

Enable validation on any DI-registered service:

public class MyService : ITransientDependency, IValidationEnabled
{
    public virtual async Task DoItAsync(MyInput input)
    {
        // input is automatically validated
    }
}

Requirements:

  • Method must be virtual OR service used via interface
  • Class must be registered in DI (implements ITransientDependency, ISingletonDependency, or IScopedDependency)
Enabling/Disabling Validation
public class MyService : ITransientDependency, IValidationEnabled
{
    public bool IsValidationEnabled { get; set; } = true; // Default

    public virtual async Task DoItAsync(MyInput input) { }
}
AbpValidationException

Thrown automatically when validation fails:

public class AbpValidationException : AbpException, IHasValidationErrors
{
    public IList<ValidationResult> ValidationErrors { get; }
}
  • Implements IHasValidationErrors — errors serialized in API response
  • Automatically handled by ABP's exception handler
  • Returns HTTP 400 with validation error details

Validation Error Response Format
{
  "error": {
    "code": "App:010046",
    "message": "Your request is not valid, please correct and try again!",
    "validationErrors": [
      {
        "message": "Username should be minimum length of 3.",
        "members": ["userName"]
      },
      {
        "message": "Password is required",
        "members": ["password"]
      }
    ]
  }
}

Best Practices
  1. Use Data Annotations for simple, declarative validation (required, length, range)
  2. Use FluentValidation for complex validation rules, cross-property validation
  3. Use IValidatableObject sparingly — only when validation is tightly coupled to the DTO
  4. Keep domain validation in domain services, not in DTOs
  5. Enable validation on application services — they are validated by default
  6. Use IValidationEnabled on custom services that need input validation
  7. Methods must be virtual for interception-based validation to work
  8. Localize validation messages using resource files for multi-language support

Validation + Exception Handling Flow
Client Request
    ↓
DTO Deserialization
    ↓
ABP Validation Interceptor
    ↓ (if invalid)
AbpValidationException thrown
    ↓
ABP Exception Handler
    ↓
HTTP 400 + validationErrors JSON
    ↓
Client receives structured error

Common Validation Attributes Reference

| Attribute | Purpose | Example | |---|---|---| | [Required] | Non-null, non-empty | [Required] public string Name { get; set; } | | [StringLength(max)] | Max length | [StringLength(100)] | | [StringLength(min, max)] | Min/max length | [StringLength(3, 100)] | | [Range(min, max)] | Numeric range | [Range(0, 999.99)] | | [EmailAddress] | Email format | [EmailAddress] | | [RegularExpression(pattern)] | Regex match | [RegularExpression(@"^[a-zA-Z]+$")] | | [MinLength(n)] | Minimum collection/string length | [MinLength(3)] | | [MaxLength(n)] | Maximum collection/string length | [MaxLength(100)] | | [Url] | URL format | [Url] | | [Phone] | Phone format | [Phone] |


Related
  • [Exception Handling](../abp-exception-handling/SKILL.md) — How validation errors are handled
  • FluentValidation — External validation library docs
  • ASP.NET Core Validation — Microsoft's validation documentation
按 MIT 许可原样转载,未经改动 · 在 GitHub 查看 →

评论

登录即可评论;带「已验证安装」的,是发布者名下有本店的安装或持有记录。