自定义验证属性从未验证

时间:2018-09-25 09:52:42

标签: c# asp.net .net .net-core

我试图创建一个自定义验证属性,以仅要求一个字段,具体取决于另一个字段的结果。

我遇到的问题是,从来没有调用过IsValid块。数据似乎正在进入领域,我已经能够使用断点进行检查。

我尝试将TryValidateModel(this)放在OnPostAsync中,这可以通过断点,但是我可以看到发生了另一个错误。

  

请求的操作对DynamicMethod无效

这是我下面的代码。任何帮助将不胜感激。

        public class PageOneModel : PageModel
        {
            [BindProperty]
            public bool CompanyHouseToggle { get; set; }

            [BindProperty]
            [StringLength(60, MinimumLength = 3)]
            [RequiredIf("CompanyHouseToggle", desiredvalue: "true")]
            public string CompanyNumber { get; set; }

            [BindProperty]
            [StringLength(60, MinimumLength = 3)]
            public string OrganisationName { get; set; }

            [BindProperty]
            [RegularExpression(pattern: "(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})", ErrorMessage = "This VAT number is not recognised")]
            public string VatNumber { get; set; }

            public void OnGet()
            {
            }

            public async Task<IActionResult> OnPostAsync()
            {
                if (!ModelState.IsValid)
                {
                    return Page();
                }

                RedirectToPage("2");
            }
        }

        public class RequiredIfAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
        {
            private String PropertyName { get; set; }
            private Object DesiredValue { get; set; }

            public RequiredIfAttribute(String propertyName, Object desiredvalue)
            {
                this.PropertyName = propertyName;
                this.DesiredValue = desiredvalue;
            }

            protected override ValidationResult IsValid(object value, ValidationContext context)
            {
                var property = context.ObjectType.GetProperty(PropertyName);

                if (property == null)
                    throw new ArgumentException("Property with this name not found");

                // Just for testing purposes.
                return new ValidationResult(ErrorMessage);

            }
        }

1 个答案:

答案 0 :(得分:0)

我建议您从ReuiredAttribute继承。它完全适合我。

public class RequiredUnlessDeletingAttribute : RequiredAttribute
{
    string DeletingProperty;

    /// <summary>
    /// Check if the object is going to be deleted skip the validation.
    /// </summary>
    /// <param name="deletingProperty">The boolean property`s name which shows the object will be deleted.</param>
    public RequiredUnlessDeletingAttribute(string deletingProperty = "MustBeDeleted") =>
        DeletingProperty = deletingProperty;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(deletingProperty);

        if ((bool)property.GetValue(validationContext.ObjectInstance))
            return ValidationResult.Success;

        return base.IsValid(value, validationContext);

    }
}

检查完整的实施here