2016-09-13 39 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