简体   繁体   English

System.ComponentModel.DataAnnotations 验证属性未按预期工作

[英]System.ComponentModel.DataAnnotations validation attributes not working as expected

I have checked for possible solutions to this and haven't been able to get any meaningful solution.我已经检查了可能的解决方案,但无法获得任何有意义的解决方案。 I am working on an ASP.NET Web API project and I have a controller route with the below method signature:我正在处理一个 ASP.NET Web API 项目,并且我有一个具有以下方法签名的控制器路由:

[HttpPost("cimgAirtimeVending/{msisdn}")]
public async Task<ActionResult<ResponseObject>> CIMGAirtimeVending([FromBody] CIMGBillPaymentRequest _cimgAirtimeBillPaymentRequest, [Required, RegularExpression(@"\d{13}")] string msisdn)

CIMGBillPaymentRequest is a DTO with validations defined on each property as follows: CIMGBillPaymentRequest是一个 DTO,在每个属性上定义了如下验证:

public class CIMGBillPaymentRequest
{
    [Required, RegularExpression(@"\w+"), StringLength(30)]
    public string RequestId { get; set; }
    
    [Required, StringLength(10, MinimumLength = 10), RegularExpression(@"\d+")]
    public string DebitAccount { get; set; }
    
    /* [Required, RegularExpression(@"\w+")]
    public string Narration { get; set; } */
    
    [Required]
    public bool IsFees { get; set; }
    
    public List<Charge> Charges { get; set; }
    
    [Required, RegularExpression(@"[\w-]+")]
    public string ProductId { get; set; }
    
    [Required, Range(1, 100, ErrorMessage = "Enter valid ChannelId")]
    public int ChannelId { get; set; }
    
    // [Required, Range(100, 100000, ErrorMessage = "Enter valid Amount (>=100)")]
    public decimal Amount { get; set; }
    
    [Required, RegularExpression(@"\w+")]
    public string CustomerReference { get; set; }
}
public class Charge
{
    // [StringLength(10, MinimumLength = 10), RegularExpression(@"\d{10,}")]
    [RegularExpression(@"\w+")]
    public string Account { get; set; }
        
    public decimal Fee { get; set; }
}

The strange thing is, it appears not all the validation works.奇怪的是,似乎并非所有验证都有效。 If isFees is removed from the DTO, it should return a Required validation error, but that does not happen.如果从 DTO 中删除了isFees ,它应该返回一个Required验证错误,但这不会发生。 The validation is completely ignored.验证被完全忽略。 This does not happen with the ProductId property. ProductId属性不会发生这种情况。 A Required validation error is returned if it is not included in the DTO如果未包含在 DTO 中,则返回Required验证错误

Another issue I had was with the Account property in the Charge class.我遇到的另一个问题是Charge类中的Account属性。 If you look at the line commented above it, you will see I am using a Regex validation RegularExpression(@"\\d{10,}")] ie to ensure that it is a string of at least 10 digits.如果您查看上面注释的行,您会看到我正在使用 Regex 验证RegularExpression(@"\\d{10,}")]即确保它是至少 10 位数字的字符串。 However, this validation is completely ignored and I had to use [RegularExpression(@"\\w+")] .但是,此验证完全被忽略,我不得不使用[RegularExpression(@"\\w+")]

Any idea what the issue is and possible solution?知道问题是什么以及可能的解决方案吗?

Take a look at the documentation here .看看这里的文档。

"The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters." “RequiredAttribute 特性指定在验证表单上的字段时,该字段必须包含一个值。如果该属性为 null、包含空字符串 ("") 或仅包含空白字符,则会引发验证异常。 ”

"If the MVC data model or entity partial class contains a field that is annotated with the RequiredAttribute attribute, but the page does not contain the property, an error is not raised. Validation occurs only for fields that are submitted to the server." “如果 MVC 数据模型或实体部分类包含使用 RequiredAttribute 属性注释的字段,但页面不包含该属性,则不会引发错误。仅对提交给服务器的字段进行验证。”

If you leave out the property entirely then the required validation will not trigger.如果您完全忽略该属性,则不会触发所需的验证。 It will only trigger when explicitly called with null, empty string or string with only whitespace.它只会在使用 null、空字符串或只有空格的字符串显式调用时触发。 Therefore I'm assuming the required check on some other fields namely the struct fields also don't work, however when you then check for a range, like with the ChannelId property it will validate the range.因此,我假设对其他一些字段进行必需的检查,即结构字段也不起作用,但是当您检查范围时,就像使用 ChannelId 属性一样,它将验证该范围。 The issue here is that a struct can never be null.这里的问题是结构永远不能为空。 This means the RequiredAttribute won't work on bool, int, decimal, etc. fields.这意味着 RequiredAttribute 不适用于 bool、int、decimal 等字段。

In this case when not providing anything for IsFees will set the property with the value default(bool) the default value for a bool is false .在这种情况下,当不为IsFees提供任何内容时,将使用值default(bool)设置属性, default(bool)的默认值为false

As for the Account field, look at the documentation here至于 Account 字段,请查看此处的文档

"You apply the RegularExpressionAttribute attribute to a property when you need to validate values for the property against a regular expression. The regular expression enables you to specify very precisely the format of valid values. The Pattern property contains the regular expression. If the value of the property is null or an empty string (""), the value automatically passes validation for the RegularExpressionAttribute attribute. To validate that the value is not null or an empty string, use the RequiredAttribute attribute." “当您需要根据正则表达式验证属性的值时,您可以将 RegularExpressionAttribute 特性应用于属性。正则表达式使您能够非常精确地指定有效值的格式。Pattern 属性包含正则表达式。如果值为属性为 null 或空字符串 (""),该值会自动通过对 RegularExpressionAttribute 特性的验证。要验证该值不是 null 或空字符串,请使用 RequiredAttribute 特性。

When providing null, or an empty string to a field with RegularExpressionAttribute it will pass the check.当为具有RegularExpressionAttribute的字段提供 null 或空字符串时,它将通过检查。 This means, for your Account field you need to use [Required, RegularExpression(@"\\d{10,}")] .这意味着,对于您的帐户字段,您需要使用[Required, RegularExpression(@"\\d{10,}")]

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

相关问题 使用System.ComponentModel.DataAnnotations的验证摘要; - Validation Summary using System.ComponentModel.DataAnnotations; 找不到System.ComponentModel.DataAnnotations - System.ComponentModel.DataAnnotations was not found 表单验证System.ComponentModel.DataAnnotations和JQuery提交 - Forms validation System.ComponentModel.DataAnnotations and JQuery submit System.ComponentModel.DataAnnotations中的验证基础的自定义层 - Custom Layer of Validation base in System.ComponentModel.DataAnnotations 验证不会触发(System.ComponentModel.DataAnnotations) - Validation doesn't fire (System.ComponentModel.DataAnnotations) 使用 .netstandard nuget 包 system.componentmodel.dataannotations 的 C# Asp.Net 属性模型验证不起作用 - C# Asp.Net attributes model validation using .netstandard nuget package system.componentmodel.dataannotations does not work System.ComponentModel.DataAnnotations命名空间不存在 - the System.ComponentModel.DataAnnotations namespace does not exist 使用 System.ComponentModel.DataAnnotations 进行模型绑定 - Model binding using System.ComponentModel.DataAnnotations System.ComponentModel.DataAnnotations MaxLength未显示 - System.ComponentModel.DataAnnotations MaxLength not showing Mono将何时支持System.ComponentModel.DataAnnotations? - When will Mono support System.ComponentModel.DataAnnotations?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM