2016-09-13 12 views
3

クラスの一部のプロパティに値が含まれているか、範囲内にあることを確認する簡単な方法が必要でした(長さは50文字以下)。私はHow to validate Class properties?の質問と回答を使用しましたが残念ながら私はそれを動作させることができませんでした。クラスプロパティの必須フィールドを検証する方法は?

これをテストするために、私は非常に単純なWinFormのサンプルをC#で作成しました。私はすべて同じことをしていますが、間違った値を適用すると(つまり、許容限度を超えて年齢を設定するなど)、検証例外が発生することはありません。

誰かが例外をスローしない理由を説明できますか?クラスが必要な属性を使用するはずであることをクラスが知らないかのようです。

の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/manual-validation-with-data-annotations.aspx)。 – Michael

+0

@Michael - あなたのリンクに問題解決のための情報が含まれているので、あなたは答えを作成できますか? – ThePeter

+0

あなた自身の回答を投稿し、遅れてそれを自己承諾することもできます。これは、将来の読者に役立つ質問に答えたものをマークします。 – Tim

答えて

3

新しいメソッドをPersonクラスに追加して、検証を実行します。新しい「検証」メソッドは、必要な値、範囲、および文字列の長さに対して機能します。

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()); 
    } 
} 
} 

戻るフォームの背後にあるコードで、あなただけの各クラスのValidateメソッドを呼び出す必要があります。 [手動でトリガ検証]

の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

@ビッグダディ - 助けてくれてありがとう。答えに私を助けてくれました。私は助けに感謝します! :) – ThePeter

関連する問題