欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net mvc FluentValidation 的使用

程序员文章站 2022-03-04 13:07:21
...

原文

  1. Create a new ASP.NET MVC 3  project using the default Visual Studio Template
  2. Download the latest FluentValidation.NET
  3. Reference the FluentValidation.dll and FluentValidation.Mvc.dll assemblies (be careful there are two folders inside the .zip: MVC2 and MVC3 so make sure to pick the proper assembly)

 

新建一个Model

[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
	public string Title {get;set;}
}

以及相应的Validator

public class MyViewModelValidator:AbstractValidator<MyViewModel>
{
	public MyViewModelValidator()
	{
		RuleFor(x=>x.Title)
		.NotEmpty().WithMessage("pls enter title!")
		.Length(1,5).WithMessage("less than 5 and more than 1");
	}
}

在 Glabal.ass Application_Start中添加

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;


ModelValidatorProviders.Providers.Add(
    new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));

ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
    new AttributedValidatorFactory());

 

页面代码

@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" />
}

转载于:https://www.cnblogs.com/philzhou/archive/2012/05/08/2490253.html