簡體   English   中英

使用FluentValidation根據值驗證對象

[英]Validate an object based on a value using FluentValidation

我的數據庫中有一個具有特定規則設置的通用對象。 我想根據對象中的值在數據庫中執行特定的規則設置。

例如,假設我有一個這樣的對象

public class MyObject {
    public int Type { get; set; }
    public string Name { get; set; }
    public decimal? Value { get; set; }
}

現在,如果Type的值為0,那么我需要確保然后填充Name。 如果Type為1,那么我需要確保Name被填充並且超過50個字符,並且還需要Value進行填充。

這是一個基本示例,並且還有更多規則。 到目前為止,我有

public class MyObjectValidator : AbstractValidator<MyObject>
{
    public MyObjectValidator()
    {
        // here i would like to check what the value of type is, something like
        if (Type == 1) {
            RuleFor(e => e.Name).NotEmpty().WithMessage("Please enter a name");
        }

        if (Type == 2) {
            RuleFor(....);
        }
    }
}

但是我不知道如何獲取正在驗證的實例。

我的確很適合您的工作。

public class MyObjectValidator : AbstractValidator<MyObject>
    {
        public MyObjectValidator()
        {
            RuleFor(x => x.Name).NotEmpty().When(m => m.Type == 1).WithMessage("your msg");
            RuleFor(x => x.Name).Must(s => s.Length > 50).When(m => m.Type == 2).WithMessage("your msg");;
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM