asp.net mvc 中的最小值/最大值验证器 [英] Min/Max-value validators in asp.net mvc

查看:18
本文介绍了asp.net mvc 中的最小值/最大值验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 asp.net mvc 中使用属性进行验证非常好.到目前为止,我一直在使用 [Range(min, max)] 验证器来检查值,例如:

Validation using attributes in asp.net mvc is really nice. I have been using the [Range(min, max)] validator this far for checking values, like e.g.:

[Range(1, 10)]
public int SomeNumber { get; set; }

但是 - 现在我需要分别检查最小和最大条件.我希望找到这样的属性:

However - now I need to check the min and max condition separately. I expected to find attributes like these:

[MinValue(1, "Value must be at least 1")]
[MaxValue(10, "Value can't be more than 10")]
public int SomeNumber { get; set; }

是否有任何预定义的属性来编写这个?或者我如何实现这一目标?

Are there any predefined attributes for writing this? Or how do I achieve this?

推荐答案

这是我为 MaxValue 编写验证器的方法

Here is how I would write a validator for MaxValue

public class MaxValueAttribute : ValidationAttribute
    {
        private readonly int _maxValue;

        public MaxValueAttribute(int maxValue)
        {
            _maxValue = maxValue;
        }

        public override bool IsValid(object value)
        {
            return (int) value <= _maxValue;
        }
    }

MinValue 属性应该完全相同

The MinValue Attribute should be fairly the same

这篇关于asp.net mvc 中的最小值/最大值验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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