Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc .NET mvc3验证最小长度,但不是必需的_Asp.net Mvc_Asp.net Mvc 3_Validation - Fatal编程技术网

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

Asp.net mvc .NET mvc3验证最小长度,但不是必需的,asp.net-mvc,asp.net-mvc-3,validation,Asp.net Mvc,Asp.net Mvc 3,Validation,我目前正在使用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

我目前正在使用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]

没有帮助。有没有办法在不创建另一个自定义验证属性的情况下执行此操作?

您正在查找的注释

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

属性的字符串值似乎为空或空白,因为
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);
}
public override bool有效(对象值)
{
这。确保长度();
整数长度=0;
如果(值==null)
{
返回true;/=此.Length);
}

非常确定MinLength属性假定为Requiredhuh…我以前有过,但它不起作用。但现在它起作用了!我觉得很傻。所以问题又出现了,这是正确的答案:)