I created an HtmlHelper for the label, which puts a star after the name of this label, if the corresponding field is required:
public static MvcHtmlString LabelForR<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { return LabelHelper( html, ModelMetadata.FromLambdaExpression(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), null); } private static MvcHtmlString LabelHelper(HtmlHelper helper, ModelMetadata metadata, string htmlFieldName, string text) { ...
If I use DataAnnotations and slap [Required] for the property in my ViewModel, the metadata.IsRequired in my personal LabelHelper will be True, and everything will work as intended.
However, if I use FluentValidation 3.1 and add a simple rule:
public class CheckEmailViewModelValidator : AbstractValidator<CheckEmailViewModel> { public CheckEmailViewModelValidator() { RuleFor(m => m.Email) .NotNull() .EmailAddress(); } }
... the LabelHelper.IsRequired metadata will be incorrectly set to false. (The validator works though: you cannot send an empty field, and it should look like an email).
The rest of the metadata looks correct (for example: metadata.DisplayName = "Email").
In theory, the FluentValidator uses the RequiredAttribute on property if the .NotNull () rule is used.
For reference: My ViewModel:
[Validator(typeof(CheckEmailViewModelValidator))] public class CheckEmailViewModel {
My controller:
public class MemberController : Controller { [HttpGet] public ActionResult CheckEmail() { var model = new CheckEmailViewModel(); return View(model); } }
Any help is appreciated.