【问题标题】:Validation MinLength, but not Required验证最小长度,但不是必需的
【发布时间】:2018-12-17 09:19:14
【问题描述】:

如何创建一个不需要的数据字段,但如果字符串不为空则有最小和最大长度要求。

我已阅读此.NET mvc3 validation minimumlength, but not required,但它是针对 .net mvc3 的,我认为可能会有一个新的更复杂的解决方案。

    [MinLength(6, ErrorMessage = "Минимално 6 символа")]
    [StringLength(12, ErrorMessage = "Максимално 12 символа")]
    [Display(Name = nameof(TextResources.Egn), ResourceType = typeof(TextResources))]
    public string ClientIdentifier { get; set; }

【问题讨论】:

  • 验证在哪里进行?这是在“控制器”级别还是在某些数据库实体级别?如果是某种控制器验证,请查看 FluentValidations .When 子句。 fluentvalidation.net/start#conditions
  • @jpgrassi 它发生在控制器级别
  • @Venkatesh 抱歉,我不喜欢抛出异常的想法。我已经使用自定义属性完成了它,但仍然没有时间在这里发布它。
  • @Xueli Chen 我也没试过解决办法
  • @stefan.stt 尽快发布您的答案

标签: asp.net-core


【解决方案1】:

对于这种情况而不是验证属性,请使用自定义方法并在初始化期间调用该方法。

   if(!string.Isnullorempty(ClientIdentifier))
   {
             if()//check min and max length

                throw exception
   }

【讨论】:

    【解决方案2】:

    尝试更改您的代码,如下所示,StringLength 属性可让您设置字符串属性的最大长度,以及可选的最小长度。

    [StringLength(12, MinimumLength = 6, ErrorMessage = "The field must be a string with a minimumLength of 6 and a maxmumLength of 12")]
    
    [Display(Name = nameof(TextResources.Egn), ResourceType = typeof(TextResources))]
    public string ClientIdentifier { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 2011-06-25
      相关资源
      最近更新 更多