Fluent Validation - 自定义 Guid 验证器未触发

phi*_*con 1 asp.net fluentvalidation asp.net-core

我有一个自定义的 FleuntValidation 验证规则,用于检查 Guid 是否有效;

 public static class GuidValidator
{
    private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
    public static bool IsGuid(string candidate)
    {
        if (candidate != null)
        {
            if (isGuid.IsMatch(candidate))
            {
                return true;
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用它来检查 Guid 属性是否有效,然后返回自定义错误消息。

RuleFor(x => x.ShiftId).Must(guid => GuidValidator.IsGuid(guid.ToString())).WithMessage("StopShift.ShiftId.GuidNotValid()");
Run Code Online (Sandbox Code Playgroud)

但是,我的规则没有受到影响,因为我猜 Guid 无效,并且一些内置检查在它之前运行。我如何禁用内置检查以便达到我的自定义规则?

小智 6

这取决于你的堆栈是什么样的。AGuid不会被实例化为“无效”值。

如果您想满足相关值可以是有效或无效的用例,Guid我建议您将其建模为字符串。

例如

[Validator(typeof(FooRequestValidator))]
public class FooRequest
{
    public string Bar { get; set; }
}

public class FooRequestValidator : AbstractValidator<FooRequest>
{
    public FooRequestValidator()
    {
        RuleFor(x => x.Bar)
            .Must(ValidateBar).WithErrorCode("Not a guid");
    }

    private bool ValidateBar(string bar)
    {
        return Guid.TryParse(bar, out _);
    }
}
Run Code Online (Sandbox Code Playgroud)