自定义服务器端验证 MVC Entity Framework

Custom Server Side Validation MVC Entity Framework

我正在尝试连接一些服务器端验证,因此存在某种最后一道防线,因此不良数据无法通过。我的字段之一取决于布尔值。如果布尔值为真,则 int 值必须为 0。如果为假,则它必须介于 1 和 7 之间。这是我目前所拥有的,但它不起作用。

[ValidApplicationPrimary(ComplianceProfile= NFlagComplianceProfile)]
[Column("APPLICATION_PRIMARY")]
public int ApplicationPrimary { get; set; }

[Required]
[Column("NFLAG_COMPLIANCE_PROFILE")]
public bool NFlagComplianceProfile { get; set; }

public class ValidApplicationPrimary : ValidationAttribute
    {
        public Boolean ComplianceProfile { get; set; } 

        public override bool IsValid(object value)
        {
            if (ComplianceProfile)//If they have a compliance profile the value of Application Primary should be 0
            {
                if (((Int32)value) == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else if (((Int32)value) > 0 && ((Int32)value)<=7) //If Application primary is between 1 and 7 then it is true
            {
                return true;
            }
            else //Outside that range its false
                return false;

        }

我一直收到这个错误

Error   3   An object reference is required for the non-static field, method, or property 'EntityFrameworkTable.NFlagComplianceProfile.get'

如果您还没有,您应该考虑使用 Jeremy Skinner 的 FluentValidation。非常轻巧,将显着简化您的验证规则。

FluentValidation github

完成初始设置和模型装饰后,您可以将规则放入验证器的构造函数中。您甚至可以定义自定义验证方法以有条件地应用验证规则。这在文档中有更详细的解释。

public class ObjectValidator : AbstractValidator<YourObject>
{    
    public ObjectValidator(){
      RuleFor(x => x.ApplicationPrimary).Equal(0).When(x => x.NFlagComplianceProfile);
      RuleFor(x => x.ApplicationPrimary).InclusiveBetween(1, 7).When(x => !x.NFlagComplianceProfile);    
    }
}

你会这样装饰你的模型

[Validator(typeof(ObjectValidator))]
public class YourObject
{
   public int ApplicationPrimary { get; set; }

   public bool NFlagComplianceProfile { get; set; }
}

您不能以这种方式引用其他属性。如果您有 .NET 4 或更高版本,您可以这样做:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidApplicationPrimary : ValidationAttribute
{
  private const string DefaultErrorMessage = "If {0} is false, {1} must be 1-7.";

  public bool ComplianceProfile { get; private set; }

  public override string FormatErrorMessage(string name)
  {
    return string.Format(ErrorMessageString, name, ComplianceProfile );
  }

  protected override ValidationResult IsValid(object value, 
                        ValidationContext validationContext)
  {
    if (value != null)
    {
      var complianceProfile= validationContext.ObjectInstance.GetType()
                         .GetProperty(ComplianceProfile);

      var complianceProfileValue= complianceProfile
                    .GetValue(validationContext.ObjectInstance, null);

        if (complianceProfileValue)//If they have a compliance profile the value of Application Primary should be 0
        {
            if (((Int32)value) == 0)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
        }
        else if (((Int32)value) > 0 && ((Int32)value)<=7) //If Application primary is between 1 and 7 then it is true
        {
            return ValidationResult.Success;
        }
        else //Outside that range its false
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));


    }

    return ValidationResult.Success;
  }        
}

用法:

[ValidApplicationPrimary("ComplianceProfile")]
[Column("APPLICATION_PRIMARY")]
public int ApplicationPrimary { get; set; }

本文详细介绍:http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

 public class ValidApplicationPrimary : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Boolean flag = false;
            Object instance = validationContext.ObjectInstance;
            Type type = instance.GetType();
            PropertyInfo property = type.GetProperty("NFlagComplianceProfile");
            Object propertyValue = property.GetValue(instance);

            switch (Convert.ToInt32(propertyValue))
            {
                case 1:
                    if(Convert.ToInt32(value) == 0)
                    {
                        flag = true;
                    }
                    break;
                case 0:
                    if(Convert.ToInt32(value) >0 && Convert.ToInt32(value)<8)
                    {
                        flag = true;
                    }
                    break;
                default:
                    flag = false;
                    break;
            }
            if(!flag)
            {
                ValidationResult result = new ValidationResult("");
                return result;
            }
            else
            {
                return null;
            }


        }

http://www.binaryintellect.net/articles/55bef03e-3d41-4a0a-b874-78b7c7a9ce36.aspx

这似乎对我有用。有一些问题,但我尝试过的几个不同场景似乎都能正常工作。