1

目前我有一个用户可以部分创建的客户类,并完成详细信息。例如它看起来像这样

新客户

    [Required(ErrorMessage = "Business name is required.")]
    [Display(Name = "Business Name:")]
    public string BusinessName { get; set; }

    [Display(Name = "Address:")]
    public string Address { get; set; }

    [Display(Name = "City:")]
    public string City { get; set; }

    [Display(Name = "State:")]
    public string State { get; set; }

    [Display(Name = "Zip:")]
    public string Zip { get; set; }

客户结帐

    [Required(ErrorMessage = "Business name is required.")]
    [Display(Name = "Business Name:")]
    public string BusinessName { get; set; }

    [Required(ErrorMessage = "Address is required.")]
    [Display(Name = "Address:")]
    public string Address { get; set; }

    [Required(ErrorMessage = "City is required.")]
    [Display(Name = "City:")]
    public string City { get; set; }

    [Required(ErrorMessage = "State is required.")]
    [Display(Name = "State:")]
    public string State { get; set; }

    [Required(ErrorMessage = "Zip is required.")]
    [Display(Name = "Zip:")]
    public string Zip { get; set; }

当用户结帐时,我需要确保他们完成填写信息(如果缺少某些信息)。我的想法是创建一个 Customer Checkout 类,其中填充了他们创建新客户时的信息,并在将它们传递给结账之前检查它是否有效。我的问题是我知道的唯一方法是对照 string.isNullOrEmpty() 检查每个字段,但我知道必须有更好的方法。我将不得不检查 25 个这样的字段。我知道您可以检查模型是否有效,但我需要在我的数据访问层检查中的类级别执行此操作,以确保所有 [必需] 字段都有数据。希望我只是忽略了一些东西

几乎就像我需要一些方法来做类似的事情

bool hasErrors = false 

foreach attribute in my class 
if it is marked as [required]
check to make sure not null or empty
if it is set hasErrors = true

谢谢!

4

2 回答 2

2

您需要为您的模型创建自定义验证,

实现接口IValidatableObject并覆盖实现方法Validate并创建您的自定义验证,例如

public class Foo : IValidatableObject
{

      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
      {
          //make your custom rules for validation on server side
        if ((fooAttribute== true) && (fooAtribute2 == String.Empty))
        {
            yield return new ValidationResult("Your custom Error");
        }
      }

} 

NOTE: 这样您就可以在应用程序的服务器端实现验证

于 2012-05-24T15:31:39.137 回答
1

如果不考虑性能,您可以使用反射来自动验证您的对象。

static class ObjectValidator
{
    public static bool IsValid(object toValidate)
    {
        Type type = toValidate.GetType();
        var properties = type.GetProperties();
        foreach(var propInfo in properties)
        {
            var required = propInfo.GetCustomAttributes(typeof(RequiredAttribute), false);
            if (required.Length > 0)
            {
                var value = propInfo.GetValue(toValidate, null);
                // Here you'll need to expand the tests if you want for types like string
                if (value == default(propInfo.PropertyType))
                    return false;
            }
        }
        return true;
    }
}
于 2012-05-24T16:36:25.197 回答