【问题标题】:.NET mvc3 validation minimumlength, but not required.NET mvc3 验证最小长度,但不是必需的
【发布时间】:2012-11-09 03:14:50
【问题描述】:

我目前正在使用 MVC 数据注释对我的模型执行验证。

[MinLength(4, ErrorMessage = "The {0} must be at least {2} characters long")]
[MaxLength(16, ErrorMessage = "The {0} must be {2} characters long or less")] 
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string Password { get; set; }

但是,我无法处理一个不需要的字段,但当输入字段中有内容时需要有一个 MinLength。简单地删除

[Required]

没有帮助。有没有办法在不创建另一个自定义验证属性的情况下做到这一点?

【问题讨论】:

  • 非常确定 MinLength 属性假定为必需

标签: asp.net-mvc asp.net-mvc-3 validation


【解决方案1】:

似乎您的属性具有空或空白字符串值,因为MinLength 属性将null 视为有效值:

public override bool IsValid(object value)
{
    this.EnsureLegalLengths();
    int length = 0;
    if (value == null) 
    {
        return true; // <-- null is valid!
    }
    string str = value as string;
    if (str != null)
    {
        length = str.Length;
    }
    else
    {
        length = ((Array) value).Length;
    }
    return (length >= this.Length);
}

【讨论】:

  • 所以问题又回来了,这最终是正确的答案:)
【解决方案2】:

您要查找的注释是

[StringLength(100, ErrorMessage = "The {0} have to be {2} characters.", MinimumLength = 8)]
public string Password { get; set; }

【讨论】:

  • 嗯...我以前有过,但它不起作用。但现在是!我觉得很傻。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2012-02-02
相关资源
最近更新 更多