简体   繁体   English

验证整个类MVC3 C#

[英]Validation on an entire Class MVC3 C#

Currently i have a customer class that the user can partially create, and finish the detailed information down the line. 目前,我有一个用户可以部分创建的客户类,并完成详细信息。 For example it looks like this 例如它看起来像这样

New Customer 新客户

    [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; }

Customer Checkout 客户结账

    [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; }

when the user goes to checkout i need to make sure that they do finish filling out the information if some is missing. 当用户去结账时我需要确保他们确实填写了信息,如果缺少某些信息。 My thought process was to create a Customer Checkout class populated with the information from when they created a new customer and check to see if its valid before passing them along to checkout. 我的思考过程是创建一个Customer Checkout类,其中填充了创建新客户时的信息,并在将它们传递给结帐之前检查它是否有效。 My issue is the only way i know to do that is to check each field against string.isNullOrEmpty() but i know there has to be a better way. 我的问题是,我知道这样做的唯一方法是针对string.isNullOrEmpty()检查每个字段,但我知道必须有更好的方法。 I will have to check 25 fields like this. 我将不得不检查这样的25个字段。 I know that you can check if a Model is valid, but i need to do this at a class level in my Data Access Layer checking to make sure all[required] fields have data. 我知道您可以检查模型是否有效,但我需要在数据访问层检查中在类级别执行此操作以确保所有[必需]字段都有数据。 Hopefully i am just overlooking something 希望我只是忽略了一些东西

almost like I need some way to do something like 几乎就像我需要一些方法来做类似的事情

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

thanks! 谢谢!

You need to create a custom validation for your model, 您需要为模型创建自定义验证,

Implements the interface IValidatableObject and override the implement the method Validate and create your custom validation for example 实现接口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: With this you're achieving validation on the server side of your application NOTE: 通过此操作,您可以在应用程序的服务器端实现验证

If performance is not a consideration you can use reflection to automatically validate your object. 如果不考虑性能 ,可以使用反射来自动验证对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM