Asp.Net MVC3模型验证字符串为null,如果不是,则最小长度为x [英] Asp.Net MVC3 Model Validation string is null or if not, has min length of x

查看:90
本文介绍了Asp.Net MVC3模型验证字符串为null,如果不是,则最小长度为x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很好奇,是否可以让模型验证执行以下操作:

Just curious, is it possible to have Model Validation do the following:

NewPassword可以为null 或者 如果NewPassword不为null,则最小长度为7

NewPassword can be null OR If NewPassword is not null, then have a min length of 7

推荐答案

使用现成的功能,我认为这是不可能的.

Using the out of the box functionality, I don't believe this is possible.

但是,当然可以通过创建自己的自定义ValidationAttribute:

However, it is certainly possible by creating your own custom ValidationAttribute:

public class MinLengthOrNullAttribute : ValidationAttribute
{
    public int MinLength { get; set; }

    public MinLengthOrNullAttribute(int minLength)
    {
        MinLength = minLength;
    }

    public override Boolean IsValid(Object value)
    {
        return value == null || (value as string).Length > minLength;
    }
}

这篇关于Asp.Net MVC3模型验证字符串为null,如果不是,则最小长度为x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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