gpt4 book ai didi

asp.net-mvc - .NET mvc3 验证最小长度,但不是必需的

转载 作者:行者123 更新时间:2023-12-02 05:23:25 25 4
gpt4 key购买 nike

我目前正在使用 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 属性将 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);
}

关于asp.net-mvc - .NET mvc3 验证最小长度,但不是必需的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13483624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com