2016-09-13 68 views
3

我想要一個簡單的方法來確保某個類中的某些屬性包含值和/或在一個範圍內(即:不超過50個字符長)。我在How to validate Class properties?上使用了問題和答案,不幸的是我無法使其工作。如何驗證類屬性中的必填字段?

爲了測試它,我使用C#創建了一個非常簡單的WinForm示例。儘管我做的都是一樣的,但是當我使用不正確的值時(即:將年齡設置爲高於允許的限制),它從不會引發驗證異常。

有人可以解釋爲什麼它不拋出異常?就好像類不知道它應該使用所需的屬性。

Form1.cs的

using System; 
using System.Collections.Generic; 
using System.Windows.Forms; 
using System.ComponentModel.DataAnnotations; 

namespace RequiredFieldsInClassExample { 
public partial class Form1 : Form { 
    public Form1() { 
     InitializeComponent(); 
    } 

    private void btnTest_Click(object sender, EventArgs e) { 
     try { 
      lstStatus.Items.Clear(); 
      lstStatus.Items.Add("Creating list of people"); 
      List<Person> CollectionOfPeople = new List<Person>(); 

      lstStatus.Items.Add("Creating a good person"); 
      Person Jeff = new Person(); 
      Jeff.Age = 33; 
      Jeff.Firstname = "Jeff"; 
      Jeff.Lastname = "Jefferson"; 
      Jeff.GroupCode = "JJJ"; 

      CollectionOfPeople.Add(Jeff); 

      lstStatus.Items.Add("Creating a bad person"); 
      Person Tim = new Person(); 
      Tim.Age = 444; 
      Tim.Firstname = ""; 
      Tim.Lastname = ""; 
      Tim.GroupCode = ""; 

      CollectionOfPeople.Add(Tim); 

      lstStatus.Items.Add("Done"); 
     } catch (ValidationException Exp) { 
      MessageBox.Show(this, Exp.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } catch (Exception Exp) { 
      MessageBox.Show(this, Exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 
    } 
} 
} 

Person.cs

using System.ComponentModel.DataAnnotations; 

public class Person { 
private int m_iAge = 1; 
private string m_sFirstname = "Unknown"; 
private string m_sLastname = ""; 
private string m_sGroupCode = "AAA"; 

//[Required(ErrorMessage = "Age is a required field.")] 
//[Range(1, 100, ErrorMessage = "A persons age must be between 1 and 100.")] 
[Required, Range(1, 100)] 
public int Age 
{ 
    get { return m_iAge; } 
    set { m_iAge = value; } 
} 

//[Required(ErrorMessage = "Firstname is a required field.")] 
[Required] 
public string Firstname 
{ 
    get { return m_sFirstname; } 
    set { m_sFirstname = value; } 
} 

public string Lastname 
{ 
    get { return m_sLastname; } 
    set { m_sLastname = value; } 
} 

//[StringLength(3)] 
public string GroupCode 
{ 
    get { return m_sGroupCode; } 
    set { m_sGroupCode = value; } 
} 
} 
+0

它不會在設定值來驗證屬性,你必須[觸發手動驗證(http://odetocode.com/blogs/scott/archive/2011/ 06/29 /手動驗證與 - 數據annotations.aspx)。 – Michael

+0

@Michael - 你能否創建一個答案,因爲你的鏈接包含了允許我解決問題的信息? – ThePeter

+0

如果沒有其他答案,您也可以發佈自己的答案,並在延遲後自行接受答案。這將標誌着問題的答案,這將有助於未來的讀者。 – Tim

回答

3

將新方法添加到Person類中以執行驗證。新的「Validate」方法適用於所需的值,範圍和字符串長度。

Person.cs

using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Text; 

public class Person { 
private int m_iAge = 1; 
private string m_sFirstname = "Unknown"; 
private string m_sLastname = ""; 
private string m_sGroupCode = "AAA"; 

[Required(ErrorMessage = "Age is a required field.")] 
[Range(1, 100, ErrorMessage = "A persons age must be between 1 and 100.")] 
public int Age 
{ 
    get { return m_iAge; } 
    set { m_iAge = value; } 
} 

[Required(ErrorMessage = "Firstname is a required field.")] 
public string Firstname 
{ 
    get { return m_sFirstname; } 
    set { m_sFirstname = value; } 
} 

public string Lastname 
{ 
    get { return m_sLastname; } 
    set { m_sLastname = value; } 
} 

[StringLength(3, MinimumLength = 3)] 
public string GroupCode 
{ 
    get { return m_sGroupCode; } 
    set { m_sGroupCode = value; } 
} 

public void Validate() { 
    ValidationContext context = new ValidationContext(this, serviceProvider: null, items: null); 
    List<ValidationResult> results = new List<ValidationResult>(); 
    bool isValid = Validator.TryValidateObject(this, context, results, true); 

    if (isValid == false) { 
     StringBuilder sbrErrors = new StringBuilder(); 
     foreach (var validationResult in results) { 
      sbrErrors.AppendLine(validationResult.ErrorMessage); 
     } 
     throw new ValidationException(sbrErrors.ToString()); 
    } 
} 
} 

早在形式背後的代碼,你只需要調用每個類的驗證方法。

Form1.cs的

using System; 
using System.Collections.Generic; 
using System.Windows.Forms; 
using System.ComponentModel.DataAnnotations; 

namespace RequiredFieldsInClassExample { 
public partial class Form1 : Form { 
    public Form1() { 
     InitializeComponent(); 
    } 

    private void btnTest_Click(object sender, EventArgs e) { 
     try { 
      lstStatus.Items.Clear(); 
      lstStatus.Items.Add("Creating list of people"); 
      List<Person> CollectionOfPeople = new List<Person>(); 

      lstStatus.Items.Add("Creating a good person"); 
      Person Jeff = new Person(); 
      Jeff.Age = 33; 
      Jeff.Firstname = "Jeff"; 
      Jeff.Lastname = "Jefferson"; 
      Jeff.GroupCode = "JJJ"; 
      // LOOK! This line was added 
      Jeff.Validate(); 

      CollectionOfPeople.Add(Jeff); 

      lstStatus.Items.Add("Creating a bad person"); 
      Person Tim = new Person(); 
      Tim.Age = 444; 
      Tim.Firstname = ""; 
      Tim.Lastname = ""; 
      Tim.GroupCode = ""; 
      // LOOK! This line was added 
      Tim.Validate(); 

      CollectionOfPeople.Add(Tim); 

      lstStatus.Items.Add("Done"); 
     } catch (ValidationException Exp) { 
      MessageBox.Show(this, Exp.Message, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } catch (Exception Exp) { 
      MessageBox.Show(this, Exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 
    } 
} 
} 
0

這是一個很長的時間,因爲我已經做到了這一點,但是我會給它一個鏡頭。它認爲你需要使用System.ComponentModel.DataAnnotations.Validator類來手動驗證這個類。你也可以在需要驗證的類上實現IValidatableObject - 我喜歡這種方法。

+0

我建議你添加一個[鏈接到博客文章](http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx),它顯示了你的建議。 – Michael

+0

@Michael ...抱歉Micheal在我發佈我的回覆之前沒有看到您的評論。我實際上根據經驗和知識回答問題,而不是尋找答案。如果你想發佈類似的答案,我會很樂意刪除我的回覆。底線是這傢伙需要幫助。 –

+0

@Big Daddy - 感謝您的幫助。你幫助我指導答案。我感謝幫助! :) – ThePeter