FluentValidation一个好用的实体验证库

FluentValidation验证

参考:http://www.c-sharpcorner.com/UploadFile/3d39b4/Asp-Net-mvc-validation-using-fluent-validation/

创建一个Customer类

public class Customer
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

引用FluentValidation.dll

创建CustomerValidator

复制代码

public class CustomerValidator : AbstractValidator<Customer>
    {
        public CustomerValidator()
        {
            RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required");
            RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required");
            RuleFor(x => x.Email).EmailAddress().WithMessage("Email is not valid");
        }
    }

复制代码

创建Customer控制器

复制代码

  public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            return View();
        }
       [HttpPost]
        public ActionResult Index(Customer model)
        {
            CustomerValidator validator = new CustomerValidator();
            ValidationResult result = validator.Validate(model);
            if (result.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            else
            {
                foreach (ValidationFailure failer in result.Errors)
                {
                    ModelState.AddModelError(failer.PropertyName, failer.ErrorMessage);
                }
            }
            return View(model);
        }
    }

复制代码

View:

复制代码

@model ValidationAndMVC.Models.Customer
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@if (ViewData.ModelState.IsValid)
{
    <b>
        Name : @ViewBag.Name<br />
        Email : @ViewBag.Email
    </b>
}
@using (Html.BeginForm())
{
    <fieldset>
        <legend>Customer</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
<h2>Index</h2>

复制代码

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值