我目前正在使用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]
无济于事。有没有办法在不创建另一个自定义验证属性的情况下执行此操作?
答案 0 :(得分:3)
好像你的属性有空格或空白字符串值,因为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);
}
答案 1 :(得分:2)
您正在寻找它的注释
[StringLength(100, ErrorMessage = "The {0} have to be {2} characters.", MinimumLength = 8)]
public string Password { get; set; }