.NET MVC3验证的最小长度,但不是必需的 [英] .NET mvc3 validation minimumlength, but not required

查看:87
本文介绍了.NET MVC3验证的最小长度,但不是必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用MVC数据注释对我的模型进行验证.

I am currently using MVC Data Annotations to perform validation on my model.

[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.只需删除

However, I'm stuck dealing with a field that is not required, but needs to have a MinLength when there is something in the input field. Simply removing

[Required]

没有帮助.有什么方法可以在不创建另一个自定义验证属性的情况下做到这一点?

does not help. Is there any way to do this without creating yet another custom validation attribute?

推荐答案

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

Seems like your property has empty or white space string value, because MinLength attribute considers null as a valid value:

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);
}

这篇关于.NET MVC3验证的最小长度,但不是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆