验证整个类MVC3 C#

时间:2012-05-24 15:24:04

标签: c# .net asp.net-mvc-3 validation

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

新客户

    [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

谢谢!

2 个答案:

答案 0 :(得分: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: 这样您就可以在应用程序的服务器端实现验证

答案 1 :(得分: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;
    }
}