3

我有许多表单字段,例如电话号码和邮政编码,它们可以留空。但是,当它们被填写时,我希望它们符合严格的格式规则。

我希望为此任务使用 Fluent Validation,但我还没有找到可以执行以下操作的任何内容:

RuleFor(x => x.PhoneNumber)
  .Matches(@"^\d{3}-\d{3}-\d{4}$")
  .When(x => x.PhoneNumber.Length != 0)
  .WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”")
  .Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”");

现在,这两个都抛出“未设置对象实例的对象引用”。错误。

我是否有任何意义,或者这甚至不可能使用 FluentValidation?

4

1 回答 1

5

我认为你得到“对象引用未设置为对象的实例”。PhoneNumber当它为空时尝试评估长度属性。首先,您需要检查它是否不为空,然后才应用所有其他规则。除了您使用的正则表达式Matches(@"^\d{3}-\d{3}-\d{4}$")已经包含长度验证,因此您可以安全地删除

.Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”");

如果您删除长度规则,类似的东西应该可以工作:

When(x =>  x.PhoneNumber != null, 
   () => {
      RuleFor(x => x.PhoneNumber).Matches(@"^\d{3}-\d{3}-\d{4}$")
      .WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”");           
 });
于 2016-03-05T05:18:07.360 回答