.net 使用validator做資料校正

來源:互聯網
上載者:User

標籤:

概述

在把使用者輸入的資料存放區到資料庫之前一般都要對資料做服務端校正,於是想到了.net內建的資料校正架構validator。本文對validator的使用方法進行介紹,並分析下校正的的原理。

使用validator校正資料

首先我們建立一個需要校正的實體類代碼如下:

[Table("apple")]    public class Apple    {        public Guid Id {get;set;}        [MaxLength(3,ErrorMessage="名稱長度不能超過3個")]        public string Name {get;set;}        public string Comment {get;set;}        public virtual ICollection<Banana> Bananas { get; set; }    }

我們在Name屬性添加了一個校正中繼資料MaxLength。

然後使用下面的代碼對資料進行校正:

  Apple apple = new Apple(){Name = "tes你"};
  string strLength = "";

  List<ValidationResult> results = new List<ValidationResult>();            ValidationContext validateContext = new ValidationContext(apple);            if (Validator.TryValidateObject(apple, validateContext, results, true))            {                strLength = "it is ok!";            }

校正失敗會在 results中出現錯誤資訊。

自訂校正方法

例如上面的例子,如果我們希望是按位元組數來校正資料,而不是字串長度。我們就需要對校正方法進行擴張並自訂實現校正方法了。擴充校正方法的代碼如下:

public class NewMaxLengthAttribute : MaxLengthAttribute    {        public NewMaxLengthAttribute()            : base()        { }        public NewMaxLengthAttribute(int length)            : base(length)        { }        public override bool IsValid(object value)        {            if (value != null && value is string  )            {                int byteLength = System.Text.Encoding.Default.GetByteCount(value.ToString());                if (  byteLength > base.Length )                {                     return false;                }             }             return true;         }    }

對MaxLengthAttribute進行繼承,並重載校正方法IsValid即可。

validator實現原理分析

類比validator代碼如下:

 

          Apple apple = new Apple(){Name = "tes你"};         
         Type typeForTest = apple.GetType(); foreach (PropertyInfo ai in typeForTest.GetProperties()) { var test = ai.GetCustomAttribute(typeof(MaxLengthAttribute), false) as MaxLengthAttribute; var aiType = ai.GetType(); if (test != null && ai.PropertyType.Name.Equals("String")) { var length = test.Length; var propertyValue = ai.GetValue(apple).ToString(); int byteLength = System.Text.Encoding.Default.GetByteCount(propertyValue); if (length >= byteLength) { res+= " OK"; } else {
                res+= "資料不合理";
              }
            }
          }

 

利用反射讀取實體的屬性上定義的中繼資料資訊,然後對資料進行校正。

 

.net 使用validator做資料校正

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.