FluentValidation NotEmpty and EmailAddress example

ぃ、小莉子 提交于 2019-12-01 15:25:07

问题


I am using FluentValidation with a login form. The email address field is

Required and Must be a valid email address.

I want to display a custom error message in both cases.

The code I have working is:

RuleFor(customer => customer.email)
    .NotEmpty()
    .WithMessage("Email address is required.");

RuleFor(customer => customer.email)
    .EmailAddress()
    .WithMessage("A valid email address is required.");

The above code does work and shows (2) different error messages. Is there a better way of writing the multiple error message for one field?

UPDATE - WORKING

Chaining and add .WithMessage after each requirement worked.

RuleFor(customer => customer.email)
    .NotEmpty()
        .WithMessage("Email address is required.")
    .EmailAddress()
        .WithMessage("A valid email address is required.");

回答1:


You can just chain them together, it's called Fluent Validation for a reason.

RuleFor(s => s.Email).NotEmpty().WithMessage("Email address is required")
                     .EmailAddress().WithMessage("A valid email is required");


来源:https://stackoverflow.com/questions/30716202/fluentvalidation-notempty-and-emailaddress-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!