简体   繁体   English

FluentValidation中的可选验证规则

[英]Optional validation rule in FluentValidation

I have got two different models which extend an basemodel. 我有两个不同的模型扩展了基本模型。

public class basemodel 
{
   public string prename;
   public string surname;
}

public class modelA : basemodel 
{
   public string street;
   public int gender; //0 = m / 1 = f
}

public class modelB : basemodel 
{
   public string street; 
}

Now I wanna validate them in my HTTP PUT controller. 现在,我想在我的HTTP PUT控制器中验证它们。 The controller decides between the modelA or modelB depending on the role a user has (admin can see modelA and user can see modelB ). 控制器根据用户的角色来决定是在modelA还是modelB之间(管理员可以看到modelA而用户可以看到modelB )。

public ActionResult Put(MyDto myDto)
{
   if (validationSrv.IsValid(myDto, ruleSetNames: "Edit", propertyNames: null))
   {
       session.Merge(myDto);
       session.Flush();
       session.Evict(myDto);
   } //else xyz
}

My actual validator looks like this. 我的实际验证器看起来像这样。

public MyValidator() : AbstractValidator<basemodel>
{
   RuleSet("Edit", () =>
   {
       editBaseValidation();
   });
}

private void editBaseValidation()
{
   RuleFor(a => a.prename)
        .NotEmpty()
        .Length(5, 50);

   RuleFor(a => a.surname)
        .NotEmpty()
        .Length(5, 50);

   //say this is optional!
   RuleFor(a => a.street)
        .NotEmpty()

   //say this is optional!
   RuleFor(a => a.gender)
        .NotEmpty()
}

Now my question. 现在我的问题。 Is there a way to say my validator that some attributes like street or gender are optional depending on the models used? 有没有办法说出我的验证器,根据所使用的模型,某些属性(如streetgender是可选的? So I can use only the validator for the basemodel and the validator decides which attribures to validate or not. 因此,我只能对基模型使用验证器,而验证器则决定要验证的属性。

Thanks in advance :-) 提前致谢 :-)

I've found a solution to do this in another way. 我找到了另一种解决方案。 I'm using ASP.NET Core 2.1 so this is what I've found. 我正在使用ASP.NET Core 2.1,所以就是我所发现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM