MVC模型验证+客户端验证

在MVC中验证分为两种

  ->服务的验证

    创建一个基本的MVC项目,在这里不建空的是因为,空的没有我们需要的Jquery

  

  为了方便演示,我们创建了一个很简单的类Person

    public class Person
    {
        public string Name { get; set; }
    }

  然后为了实现验证,我们还必须创建一个可以提交的Index页面,

 

@using MvcApplication3.Controllers;
@model Person
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.EditorFor(d=>d.Name)@Html.ValidationMessageFor(d=>d.Name)
            <input type="submit" value="提交"/>
        }
    </div>
</body>
</html>

 

  当然现在只是说这个页面可以显示验证的消息了,可是我们还没有写怎么验证的!

    在服务端的验证分为3种

      ->1.在Action方法中直接判断

      

        [HttpPost]
        public ActionResult Index(Person p)
        {
            if (string.IsNullOrEmpty(p.Name))
            {
                ModelState.AddModelError("Name","姓名不能为空");
            }

            return View();
        }

      然后运行程序,我们就可以看到效果了!!!

 

       ->2.使用元数据验证

      

using System;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Controllers
{
    public class Person
    {
        [Required(ErrorMessage="此字段不能为空")]
        public string Name { get; set; }
    }
}

        当然MVC内置的验证有5种,分别是Required,StringLength,Compare,RegularExpression,Range

        然后我们修改Index方法

  

        [HttpPost]
        public ActionResult Index(Person p)
        {
            //if (string.IsNullOrEmpty(p.Name))
            //{
            //    ModelState.AddModelError("Name","姓名不能为空");
            //}

            return View();
        }

    运行程序,可以看到可成功了

    当然我们也可以写自己的属性验证特性,只需要实现ValidationAttribute 并实现IsValid()方法就好了

        ->3.模型验证,也就是在模型绑定的时候写验证,我们需要实现自己的绑定

using System;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication3.Controllers
{
    public class CustomValidationModelBinder : DefaultModelBinder
    {
        protected override void OnModelUpdated(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            base.OnModelUpdated(controllerContext, bindingContext);
            var person = bindingContext.Model as Person;
            if (person==null||
                bindingContext.ModelState.IsValidField("Name")||
                string.IsNullOrEmpty(person.Name))
            {
                bindingContext.ModelState.AddModelError("","模型绑定不成功");
            }
        }
    }
}

 

    有了自己的模型绑定类以后,就需要在Global中注册,

  

            ModelBinders.Binders.Add(typeof(Person), new CustomValidationModelBinder());

  修改Person后还需要修改Index.cshtml,因为我们是做的模型绑定,所有需要加上这行代码

        @Html.ValidationSummary(true)

 

using System;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Controllers
{
    public class Person
    {
        //[Required(ErrorMessage="此字段不能为空")]
        public string Name { get; set; }
    }
}

启动程序

  ->客户端验证

    开启客户端验证

    

  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

    ->1.使用元数据的方式,不过需要引用Jquery的Validation库

    ->2.实现ValidationAttributeIClientValidatable接口

    

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Controllers
{
    public class CustomValidationNameAttribute:ValidationAttribute,IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value is string&& string.IsNullOrEmpty(value.ToString());
        }
        public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, 
                                        ControllerContext context) {
return new List<ModelClientValidationRule>() { new ModelClientValidationRule(){ ErrorMessage="你这个值不是字符串吧!!!", ValidationType="required"} }; } } }
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
   //[ModelBinder(typeof(CustomValidationModelBinder))]
    public class Person
    {
        //[Required(ErrorMessage="此字段不能为空")]
        [CustomValidationName]
        public string Name { get; set; }
    }
}

   

 当然这个只是调用jq本来有的,那么现在我们自己写一个

    public class CustomValidationNameAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            bool isvalid = false;
            isvalid=string.IsNullOrEmpty(value.ToString()) ;
            try
            {
                int.Parse(value.ToString());
                isvalid = true;
            }
            catch (Exception)
            {
                isvalid = false;
            }
            return isvalid;
        }
        public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
        {
            return new List<ModelClientValidationRule>() {

            new ModelClientValidationRule(){ ErrorMessage="哥我要的是数字啊", ValidationType="int"}

            };
        }

    }

js 代码如下,核心代码

    $.validator.addMethod("int",
        function (value, element, params) {
            return !isNaN(parseFloat(value)) && isFinite(value);
        });
    $.validator.unobtrusive.adapters.add("int", function (options) {
        options.rules["int"] = {
        };
        options.messages["int"] = options.message;
    });

Hold on, everything is possible.
原文地址:https://www.cnblogs.com/student-note/p/6524085.html