asp.net mvc FluentValidation 的使用

本文详细介绍了如何在ASP.NET MVC3项目中整合FluentValidation.NET进行模型验证,包括创建模型、验证规则设置、全局配置以及前端验证提示的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值