【问题标题】:Custom validation attribute is never validated自定义验证属性永远不会被验证
【发布时间】:2018-09-25 09:52:42
【问题描述】:

我正在尝试创建一个自定义验证属性,只需要一个字段,具体取决于另一个字段的结果。

我遇到的问题是 IsValid 块永远不会被调用。数据似乎正在进入字段,我已经能够通过断点进行检查。

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

请求的操作对 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);

            }
        }

【问题讨论】:

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


    【解决方案1】:

    我建议你从 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

    【讨论】:

    • 我忘了说我也试过这个。你是对的,这意味着它确实被调用了,但现在的问题是它找不到该属性。它只是返回为空。你以前遇到过这个问题吗?不过感谢您的帮助
    • 经过更多研究,你是对的,从 ValidationAttribute 继承只会在字段有值时触发。不过仍然停留在这个 null 属性值上......
    • 我已经测试了你的代码,没有任何问题。当然,我已经从中删除了 PageModelOnPostAsyncOnGet
    • 我已经发布了另一个问题here,因为我遇到了另一个问题,但将其标记为已解决,因为您确实解决了我的初始问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多