如何使用FluentValidation仅验证类中被修改的属性?
解决FluentValidation仅验证更新时提交的属性问题
针对你在PUT更新场景下只验证提交字段的需求,可以通过条件验证结合可空属性设计来实现,具体步骤如下:
1. 设计UpdateProductCommand类
将需要更新的属性设置为可空类型(值类型需改为Nullable<T>,引用类型默认可空),这样未提交的属性会保持null,以此标记该字段无需更新:
public class UpdateProductCommand { public int Id { get; set; } // 必须提交的主键,用于定位实体 public string? Name { get; set; } // 可选更新字段 public string? Category { get; set; } // 可选更新字段 public IFormFile? ImageFile { get; set; } // 可选更新字段 public decimal? Price { get; set; } // 值类型改为可空 }
2. 编写UpdateProductCommandValidator
使用FluentValidation的When方法为每个验证规则添加执行条件:仅当对应属性不为null(即被提交更新)时,才触发验证逻辑:
public class UpdateProductCommandValidator : AbstractValidator<UpdateProductCommand> { public UpdateProductCommandValidator() { // 主键必须验证,因为更新必须指定目标实体 RuleFor(x => x.Id).GreaterThan(0).WithMessage("Product Id is required"); // 仅当Name被提交(不为null)时,验证非空 RuleFor(x => x.Name).NotEmpty().WithMessage("Name cannot be empty") .When(x => x.Name != null); // 仅当Category被提交时,验证非空 RuleFor(x => x.Category).NotEmpty().WithMessage("Category cannot be empty") .When(x => x.Category != null); // 仅当ImageFile被提交时,验证非空 RuleFor(x => x.ImageFile).NotEmpty().WithMessage("ImageFile cannot be empty") .When(x => x.ImageFile != null); // 仅当Price被提交时,验证大于0 RuleFor(x => x.Price).GreaterThan(0).WithMessage("Price must be greater than 0") .When(x => x.Price.HasValue); } }
关键逻辑说明
- 可空属性:通过将更新字段设为可空,明确区分“未提交不需要更新”和“提交了空值”两种场景。比如用户提交
Name=""会触发非空验证,但如果完全不提交Name字段,属性值为null,验证规则会直接跳过。 - When条件:
When方法限定了验证规则的执行时机,只有当属性存在有效值(被提交更新)时,才执行对应的验证逻辑,避免强制用户提交所有字段。
内容的提问来源于stack exchange,提问作者Carlos
相关产品推荐
相关产品推荐

