Aԃι*_*ɾαʋ 1 c# fluentvalidation fluentvalidation-2.0
我编写了一项规则来检查列表中的对象 Id 是否不为空或为空。但规则并没有失败。我的代码有什么问题吗?
注意:ID 是字符串类型。
RuleFor(x => x.MyListOfObjects).Must(x => x.All(x => !string.IsNullOrWhiteSpace(x.Id)))
.WithMessage("The Id should not be empty or null.");
Run Code Online (Sandbox Code Playgroud)
欢迎任何指点或建议。
小智 5
我已经为您的代码编写了可能的示例。如果您以这种方式使用流畅的验证,那么您的语句似乎一切正常(请注意,如果一项为“”或仍应用空检查):
internal static class Program
{
static void Main(string[] args)
{
var list = new ListClass();
var result = list.Validate();
if(!result.IsValid) Console.WriteLine($"Error: {result.Errors.First()}");
}
}
class ListClass
{
public List<Item> List = new List<Item>()
{
new Item {Id = "Empty"},
new Item {Id = null},
new Item {Id = ""},
};
private readonly Validator _validator = new Validator();
public ValidationResult Validate() => _validator.Validate(this);
}
class Item
{
public string Id { get; set; }
}
class Validator : AbstractValidator<ListClass>
{
public Validator()
{
RuleFor(x => x.List).Must(x => x.All(x => !string.IsNullOrWhiteSpace(x.Id)))
.WithMessage("The Id should not be empty or null.");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3592 次 |
| 最近记录: |