/// <summary>
    /// Specifies that the field must compare favourably with the named field, if objects to check are not of the same type
    /// false will be return
    /// </summary>
    public class CompareValuesAttribute : ValidationAttribute
    {
        /// <summary>
        /// The other property to compare to
        /// </summary>
        public string OtherProperty { get; set; }
 
        public CompareValues Criteria { get; set; }
 
        /// <summary>
        /// Creates the attribute
        /// </summary>
        /// <param name="otherProperty">The other property to compare to</param>
        public CompareValuesAttribute(string otherProperty, CompareValues criteria)
        {
            if (otherProperty == null)
                throw new ArgumentNullException("otherProperty");
 
            OtherProperty = otherProperty;
            Criteria = criteria;
        }
 
        /// <summary>
        /// Determines whether the specified value of the object is valid.  For this to be the case, the objects must be of the same type
        /// and satisfy the comparison criteria. Null values will return false in all cases except when both
        /// objects are null.  The objects will need to implement IComparable for the GreaterThan,LessThan,GreatThanOrEqualTo and LessThanOrEqualTo instances
        /// </summary>
        /// <param name="value">The value of the object to validate</param>
        /// <param name="validationContext">The validation context</param>
        /// <returns>A validation result if the object is invalid, null if the object is valid</returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // the the other property
            var property = validationContext.ObjectType.GetProperty(OtherProperty);
 
            // check it is not null
            if (property == null)
                return new ValidationResult(String.Format("Unknown property: {0}.", OtherProperty));
 
            // check types
            var memberName = validationContext.ObjectType.GetProperties().Where(p => p.GetCustomAttributes(false).OfType<DisplayAttribute>().Any(a => a.Name == validationContext.DisplayName)).Select(p => p.Name).FirstOrDefault();
            if (memberName == null)
            {
                memberName = validationContext.DisplayName;
            }
            if (validationContext.ObjectType.GetProperty(memberName).PropertyType != property.PropertyType)
                return new ValidationResult(String.Format("The types of {0} and {1} must be the same.", memberName, OtherProperty));
 
            // get the other value
            var other = property.GetValue(validationContext.ObjectInstance, null);
 
            // equals to comparison,
            if (Criteria == CompareValues.EqualTo)
            {
                if (Object.Equals(value, other))
                    return null;
            }
            else if (Criteria == CompareValues.NotEqualTo)
            {
                if (!Object.Equals(value, other))
                    return null;
            }
            else
            {
                // check that both objects are IComparables
                if (!(value is IComparable) || !(other is IComparable))
                    return new ValidationResult(String.Format("{0} and {1} must both implement IComparable", validationContext.DisplayName, OtherProperty));
 
                // compare the objects
                var result = Comparer.Default.Compare(value, other);
 
                switch (Criteria)
                {
                    case CompareValues.GreaterThan:
                        if (result > 0)
                            return null;
                        break;
                    case CompareValues.LessThan:
                        if (result < 0)
                            return null;
                        break;
                    case CompareValues.GreatThanOrEqualTo:
                        if (result >= 0)
                            return null;
                        break;
                    case CompareValues.LessThanOrEqualTo:
                        if (result <= 0)
                            return null;
                        break;
                }
            }
 
            // got this far must mean the items don't meet the comparison criteria
            return new ValidationResult(ErrorMessage);
        }
    }
 
    /// <summary>
    /// Indicates a comparison criteria used by the CompareValues attribute
    /// </summary>
    public enum CompareValues
    {
        EqualTo,
        NotEqualTo,
        GreaterThan,
        LessThan,
        GreatThanOrEqualTo,
        LessThanOrEqualTo
    }
复制代码
 
 
应用的时候直接在指定的属性上添加此CompareValuesAttribute标签即可
 
【注:第一个参数是要与之比较的属性名,第二个参数表示两个属性值之间的大小关系,第三个参数表示错误提示信息】
 
复制代码
public class EricSunModel
{
    [Display(Name = "Ready Time")]
    public string ReadyTime { get; set; }
 
    [CompareValues("ReadyTime", CompareValues.GreaterThan, ErrorMessage = "Close time must be later than ready time")]
    [Display(Name = "Close Time")]
    public string CloseTime { get; set; }

MVC日期比较(转)的更多相关文章

  1. MVC日期格式化的2种方式

    原文:MVC日期格式化的2种方式 假设有这样的一个类,包含DateTime类型属性,在编辑的时候,如何使JoinTime显示成我们期望的格式呢? using System; using System. ...

  2. MVC日期格式化,后台使用Newtonsoft.Json序列化日期,前端使用”f”格式化日期

    MVC控制器中,经常使用Newtonsoft.Json把对象序列化成json字符串传递到前端视图.当对象中有DateTime类型的属性时,前后台如何处理才能把DateTime类型转换成想要的格式呢? ...

  3. spring mvc日期转换(前端到后端,后端到前端)

    在做web开发的时候,页面传入的都是String类型,SpringMVC可以对一些基本的类型进行转换,但是对于日期类的转换可能就需要我们配置. 1.如果查询类使我们自己写,那么在属性前面加上@Date ...

  4. mvc日期控件datepick的几篇文章,日后再总结吧

    instinctcoder里有两篇,入门级的 http://instinctcoder.com/asp-net-mvc-4-jquery-datepicker/ http://instinctcode ...

  5. MVC日期和其它字符串格式化

    -- (月份位置不是03) string.Format("{0:D}",System.DateTime.Now) 结果为:2009年3月20日 : :: -- : -- :: st ...

  6. spring的mvc对于页面日期格式进行传值到后台

    对于spring的mvc 日期格式从页面传入后台是个问题.string类型和整形都能友好传入.但是对于日期类型date却不能传入.回报403参数不对的错误. 看例子: @RequestMapping( ...

  7. SpringBoot系列——Jackson序列化

    前言 Spring Boot提供了与三个JSON映射库的集成: Gson Jackson JSON-B Jackson是首选的默认库. 官网介绍: https://docs.spring.io/spr ...

  8. spring mvc 获取页面日期格式数据

    1.传递日期参数: 解决办法: 实体类日期属性加 @DateTimeFormat(pattern="yyyy-MM-dd") 注解 beans中加 <mvc:annotati ...

  9. spring mvc 注解访问控制器以及接收form数据的方式,包括直接接收日期类型及对象的方法

    Spring 中配置扫描器 <!-- springmvc的扫描器--> <context:component-scan base-package="com.beifeng. ...

随机推荐

  1. 5.7.2.1 Math对象

    ECMAScript还为保存数学公司公式和信息提供了一个公共位置,即Math对象.与我们在JavaScript直接编写的计算功能相比,Math对象提供的计算功能执行起来要快得多.Math对象中还提供了 ...

  2. 【Delphi内联汇编学习1】Delphi与汇编

    我一直认为Delphi功能与C++相比毫不逊色,提供了丰富的控件和类.全部API以及嵌入的汇编.最近小弟在把C版的Huffman压缩改用Delphi写时,顺便“研究”了一下Delphi的位操作和嵌入式 ...

  3. 在 Windows Azure 网站中配置动态 IP 地址限制

    我们最近对 Windows Azure 网站进行了升级,并启用了IIS8的动态 IP 限制模块.现在,开发人员可以为其网站启用并配置动态 IP 限制功能(或简称 DIPR). 可以通过以下链接查看此 ...

  4. GridView行编辑、更新、取消、删除事件使用方法

    注意:当启用编辑button时,点击编辑button后会使一整行都切换成文本框.为了是一行中的一部分是文本框,须要把以整行的全部列都转换成模板,然后删掉编辑模板中的代码.这样就能使你想编辑的列转换成文 ...

  5. SqlDataAdapter的方法之一Fill (DataSet dataset, String datatable)解释

    一.SqlDataAdapter的方法之一Fill (DataSet dataset, String datatable)解释:根据datatable名填充Dataset.myda.Fill(ds, ...

  6. C++中头文件(.h)和源文件(.cpp)都应该写些什么

    头文件(.h): 写类的声明(包括类里面的成员和方法的声明).函数原型.#define常数等,但一般来说不写出具体的实现. 在写头文件时需要注意,在开头和结尾处必须按照如下样式加上预编译语句(如下): ...

  7. vector中resize和reserve的区别,代码验证

    #include <vector> using namespace std; int main() { vector<int> resizeVect; vector<in ...

  8. Java 网络编程(五) 使用TCP/IP的套接字(Socket)进行通信

    链接地址:http://www.cnblogs.com/mengdd/archive/2013/03/10/2952616.html 使用TCP/IP的套接字(Socket)进行通信 套接字Socke ...

  9. jbpmAPI-5

    Part II. jBPM Core 5.1.概述本章介绍了API需要加载过程和执行它们.更多的细节如何定义过程本身,看看在BPMN 2.0章.与流程引擎交互(例如,开始一个过程),你需要建立一个会话 ...

  10. Mac OS X 下 TAR.GZ 方式安装 MySQL 5.7+

     方法: http://www.widlabs.com/article/mac-os-x-install-mysql-57-with-tar-gz  mysql下载地址:http://www.mysq ...