如何验证类属性中的必填字段?

时间:2016-09-13 18:19:22

标签: c# winforms validation

我想要一种简单的方法来确保类中的某些属性包含值和/或在一个范围内(即:不超过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; }
}
}

2 个答案:

答案 0 :(得分:3)

在Person类中添加一个新方法以执行验证。新的&#34;验证&#34;方法适用于所需的值,范围和字符串长度。

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

答案 1 :(得分:0)

我已经做了很长时间了,但是我会试一试。它认为您需要使用System.ComponentModel.DataAnnotations.Validator类手动验证类。您还可以在需要验证的类上实现IValidatableObject - 我喜欢这种方法。