Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 流畅验证自定义验证_C#_Asp.net Mvc 3_Validation - Fatal编程技术网

C# 流畅验证自定义验证

C# 流畅验证自定义验证,c#,asp.net-mvc-3,validation,C#,Asp.net Mvc 3,Validation,我想使用Fluent验证制定两条规则(http://fluentvalidation.codeplex.com)在我的MVC项目中 当Company和Name都为空时,不应发生任何事情。 如果其中任何一个都被填满了,那么也不会发生任何事情。 如果未填写公司或名称,则在两个位置都显示标签。(错误消息可能相同) 到目前为止我已经试过了: RuleFor(x => x.Name) .NotEmpty() .WithMessage("Please fill in the company name

我想使用Fluent验证制定两条规则(http://fluentvalidation.codeplex.com)在我的MVC项目中

当Company和Name都为空时,不应发生任何事情。 如果其中任何一个都被填满了,那么也不会发生任何事情。 如果未填写公司或名称,则在两个位置都显示标签。(错误消息可能相同)

到目前为止我已经试过了:

RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Please fill in the company name or the customer name")
.Unless(x => !string.IsNullOrWhiteSpace(x.Company));

RuleFor(x => x.Company)
.NotEmpty()
.WithMessage("Please fill in the company name or the customer name")
.Unless(x => !string.IsNullOrWhiteSpace(x.Name));
我尝试了“何时”、“必须”和“除非”的组合,但都不起作用。当我不填写任何内容时,这两个属性上不会显示任何错误


有人能帮我吗?

您可以在when条件下添加两条规则:

RuleFor(x => x.Name)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.Company))
.WithMessage("Please fill in the company name or the customer name");

RuleFor(x => x.Company)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.Name))
.WithMessage("Please fill in the company name or the customer name");

从评论来看,问题似乎在于启用客户端验证,而规则实际上在回发上起作用。如中所述,唯一受支持的客户端规则是

  • NotNull/NotEmpty
  • 匹配项(正则表达式)
  • 包括二者(范围)
  • 信用卡
  • 电子邮件
  • EqualTo(跨财产平等比较)
  • 长度
因此,基本上,您试图实现的目标是不受开箱即用支持的


请看一个自定义客户端FluentValidation规则的示例。

您好,谢谢您的回答,但我应该更清楚一些。我尝试过这种方法,但由于某种原因它不起作用。所以没有人知道如何解决这个问题(我无法重现您的问题;我已经使用您的确切规则运行了一个简单的测试,它们似乎没有问题(即,当Name和Company都为null时,测试失败)。问题可能是在将FluentValidation与ASP.NET MVC集成时,也就是说,您的任何其他规则都有效吗?这在正常情况下都有效,但我应该让大家知道,此表单是用ajax发布的(jquery validate)。我注意到某些规则,例如何时、除非和必须在服务器端执行,因此在没有总页面回发的情况下无法在客户端验证。某些规则,例如NotEmpty()确实在客户端工作,但是当,除非并且必须似乎需要一个页面回发来验证时。@Robin-表单中的输入是否在页面加载后附加到DOM?@TravisJ是的,就是这样,服务器端验证正在表单提交时json序列化到网页。