我有许多表单字段,例如电话号码和邮政编码,它们可以留空。但是,当它们被填写时,我希望它们符合严格的格式规则。
我希望为此任务使用 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?