You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6中如何实现依赖其他字段的条件必填校验

可实现该类条件校验的方案有两种,都适配ASP.NET Core 6.0环境:


1. 原生内置方案:IValidatableObject接口

无需安装任何第三方包,直接在你的Opayo交易请求模型类中实现该接口的Validate方法即可自定义所有条件校验规则,ASP.NET Core框架会自动触发校验逻辑。
示例实现:

public class OpayoTransactionRequest : IValidatableObject
{
    public string Country { get; set; }
    public string PostalCode { get; set; }
    public string State { get; set; }
    public bool BrowserJavascriptEnabled { get; set; }
    public bool? BrowserJavaEnabled { get; set; }
    public int? BrowserColorDepth { get; set; }
    public bool Save { get; set; }
    public CredentialType? CredentialType { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // country为US时state必填
        if (Country.Equals("US", StringComparison.OrdinalIgnoreCase) && string.IsNullOrWhiteSpace(State))
        {
            yield return new ValidationResult("国家为美国时州字段必填", new[] { nameof(State) });
        }
        // country不为IE时postalCode必填
        if (!Country.Equals("IE", StringComparison.OrdinalIgnoreCase) && string.IsNullOrWhiteSpace(PostalCode))
        {
            yield return new ValidationResult("国家不为爱尔兰时邮编字段必填", new[] { nameof(PostalCode) });
        }
        // browserJavascriptEnabled为true时两个浏览器字段必填
        if (BrowserJavascriptEnabled)
        {
            if (!BrowserJavaEnabled.HasValue)
            {
                yield return new ValidationResult("启用JavaScript时必须填写浏览器Java启用状态", new[] { nameof(BrowserJavaEnabled) });
            }
            if (!BrowserColorDepth.HasValue)
            {
                yield return new ValidationResult("启用JavaScript时必须填写浏览器色深", new[] { nameof(BrowserColorDepth) });
            }
        }
        // Save为true时credentialType对象必填
        if (Save && CredentialType == null)
        {
            yield return new ValidationResult("Save参数为true时必须填写credentialType对象", new[] { nameof(CredentialType) });
        }
    }
}

2. 第三方库方案:FluentValidation

如果你的校验规则数量多、逻辑复杂,推荐使用.NET生态最流行的校验库FluentValidation,原生支持条件校验,和ASP.NET Core整合度高,规则写法更简洁易维护。
使用步骤:

  1. 安装NuGet包 FluentValidation.AspNetCore
  2. 编写对应请求模型的校验器,示例如下:
public class OpayoTransactionRequestValidator : AbstractValidator<OpayoTransactionRequest>
{
    public OpayoTransactionRequestValidator()
    {
        // 州校验规则
        RuleFor(x => x.State)
            .NotEmpty()
            .When(x => x.Country.Equals("US", StringComparison.OrdinalIgnoreCase))
            .WithMessage("国家为美国时州字段必填");

        // 邮编校验规则
        RuleFor(x => x.PostalCode)
            .NotEmpty()
            .When(x => !x.Country.Equals("IE", StringComparison.OrdinalIgnoreCase))
            .WithMessage("国家不为爱尔兰时邮编字段必填");

        // 浏览器相关字段校验规则
        When(x => x.BrowserJavascriptEnabled, () =>
        {
            RuleFor(x => x.BrowserJavaEnabled).NotNull().WithMessage("启用JavaScript时必须填写浏览器Java启用状态");
            RuleFor(x => x.BrowserColorDepth).NotNull().WithMessage("启用JavaScript时必须填写浏览器色深");
        });

        // credentialType校验规则
        RuleFor(x => x.CredentialType)
            .NotNull()
            .When(x => x.Save)
            .WithMessage("Save参数为true时必须填写credentialType对象");
    }
}
  1. 在Program.cs中注册FluentValidation服务即可,框架会自动执行校验逻辑。

内容的提问来源于stack exchange,提问作者hanushic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:15:06