Works great for me. Here are the steps:
- Create a new RTM MVC 3 RTM project using the default Visual Studio template
- Download the latest version of FluentValidation.NET
- Compare the
FluentValidation.dll and FluentValidation.Mvc.dll (be careful, there are two folders inside .zip: MVC2 and MVC3, so be sure to choose the appropriate assembly)
Add Model:
[Validator(typeof(MyViewModelValidator))] public class MyViewModel { public string Title { get; set; } }
and corresponding validator:
public class MyViewModelValidator : AbstractValidator<MyViewModel> { public MyViewModelValidator() { RuleFor(x => x.Title) .NotEmpty() .WithMessage("Title is required") .Length(1, 5) .WithMessage("Title must be less than or equal to 5 characters"); } }
Add to Application_Start :
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; ModelValidatorProviders.Providers.Clear(); ModelValidatorProviders.Providers.Add( new FluentValidationModelValidatorProvider(new AttributedValidatorFactory())); ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider( new AttributedValidatorFactory());
Add Controller:
public class HomeController : Controller { public ActionResult Index() { return View(new MyViewModel()); } [HttpPost] public ActionResult Index(MyViewModel model) { return View(model); } }
and corresponding view:
@model SomeApp.Models.MyViewModel @{ ViewBag.Title = "Home Page"; } <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.TextBoxFor(x => x.Title) @Html.ValidationMessageFor(x => x.Title) <input type="submit" value="OK" /> }
Now try submitting the form, leaving the Title entry blank => client-side validation, and the βTitleβ message will appear. Now start typing => the error message will disappear. After entering more than 5 characters in the input field, the title should be less than or equal to 5 characters. So, everything works as expected.
source share