自定义服务器端验证MVC实体框架

时间:2015-07-09 14:52:00

标签: asp.net-mvc entity-framework validation server-side-validation

我试图连接一些服务器端验证,因此存在某种最后的防线,因此糟糕的数据无法通过。我的一个字段取决于布尔值。如果布尔值为true,则int值必须为0.如果为false,则它必须在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'

3 个答案:

答案 0 :(得分:2)

您无法以这种方式引用其他属性。如果您使用的是.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

答案 1 :(得分:1)

如果您还没有,则应考虑使用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; }
}

答案 2 :(得分:0)

 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

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

相关问题