Fork me on GitHub

数据验证

1、  使用  Model.isValid   验证数据是否有效,将验证权给程序员

        public ActionResult Index(Person p)
        {
            if(ModelState.IsValid)
            {
                return Content("Age=" + p.Age);
            }
            else
            {
                return Content("验证失败");
            }
            
         }

2、Attribute:提供了服务器端验证请求数据的能力,要把对应的attribute标记到Model属性上

      常用Attribute:

           (1)[Required]这个属性是必须的;

            (2)[StringLength(100)] ,字符串最大长度100

            (3)[RegularExpression(@"aa(\d)+bb")]正则表达式;

            (4)[Range(33,88)]数值范围;

            (5)[Compare("Email")]这个属性必须和Email属性值一样;

             (6)[EmailAddress] 要是邮箱地址;

             (7)[Phone] 电话号码

                验证的Attribute上都有ErrorMessage属性,用来自定义报错信息

 

3、 在Action中根据ModelState.isValid判断是否验证通过,如果没有通过,可以通过下面的方法拿到报错信息   (ModelStateDictionary使用 system.web.mvc)

    public static  class MVCHelper
    {
        public static string GetValidMsg(ModelStateDictionary modelState)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var propName in modelState.Keys)
            {
               if(modelState[propName].Errors.Count<=0)
                {
                    continue;
                }
                sb.Append("属性错误:").Append(propName).Append(":");
                foreach(ModelError modelError in modelState[propName].Errors)
                {
                    sb.Append(modelError.ErrorMessage);
                }
                sb.AppendLine();

            }
            return sb.ToString();
        }

    }
    public class Person
    {
       
        public int Id { get; set; }
        [Required(ErrorMessage = "姓名不能为空")]
        public string Name { get; set; }
   
        public int Age { get; set; }
    }
        public ActionResult Index(Person p)
        {
            if(ModelState.IsValid)
            {
                return Content("Age=" + p.Age);
            }
            else
            {
                string msg = MVCHelper.GetValidMsg(ModelState);
                return Content("验证失败"+ msg);
            }
            
         }

 

 3、 自定义验证规则 ValidationAttribute , 或者直接继承自 ValidationAttribute

       (1)如果能用正则表达式校验的直接从RegularExpressionAttribute继承;

    public class QQNumberAttribute:RegularExpressionAttribute
    {
        public QQNumberAttribute():base(@"^\d{5,10}$")
        {
            this.ErrorMessage = "{0}属性不是合法的QQ号,qq号需要5-10位数值";
            //设定ErrorMessage的默认值,使用的人也可以覆盖
        }
    }
    public class Person
    {
        [QQNumber]
        public int QQ { get; set; }
    }

 

        (2)直接继承自ValidationAttribute ,重写IsValid 方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class CNPhoneNumAttribute:ValidationAttribute
    {
        public CNPhoneNumAttribute()
        {
            this.ErrorMessage = "号码必须是固话或者手机,固话要是3-4位区号开头,手机必须是13,18开头";
        }
        public override bool IsValid(object value)
        {

            if (value is string)
            {
                string s = (string)value;
                if(s.Length==13)//手机号
                {
                    if(s.StartsWith("13")|| s.StartsWith("18"))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else if(s.Contains("-")) //固话
                {
                    string[] strs = s.Split('-');
                    if(strs[0].Length==3  || strs[0].Length == 4)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}
    public class Person
    {
        [CNPhoneNum]
        public int PhoneNum { get; set; }
    }

 

posted @ 2018-07-27 15:05  精进的小陈  阅读(221)  评论(0编辑  收藏  举报