CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个中两个属性值的比较验证
具体应用场景为:要对两个属性值的大小进行验证
代码如下所示:

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

更多细节可以参考如下链接:
http://cncrrnt.com/blog/index.php/2011/01/custom-validationattribute-for-comparing-properties/
CompareValues标签对Model中的属性进行验证的更多相关文章
- 在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个中两个属性值的比较验证 具体应用场景为:要对两个属性值的大小进行验证 代码如下所示: /// ...
- 在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现RequiredIf标签对Model中的属性进行验证 具体场景为:某一属性是否允许为null的验证,要根据另 ...
- 在.Net MVC中自定义ValidationAttribute标签对Model中的属性做验证
写一个继承与ValidationAttribute类的自定义的验证方法 MVC中传递数据时,大多数都会用Model承载数据,并且在传到控制器后,对Model进行一系列的验证. 我平时经常使用的判断方法 ...
- mvc中动态给一个Model类的属性设置验证
原文:mvc中动态给一个Model类的属性设置验证 在mvc中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...
- 将DataRow赋值给model中同名属性
/// <summary> /// 将DataRow赋值给model中同名属性 /// </summary> /// <typeparam name="T&qu ...
- Implement Property Value Validation in the Application Model 在应用程序模型中实现属性值验证
In this lesson, you will learn how to check whether or not a property value satisfies a particular r ...
- Implement Property Value Validation in Code 在代码中实现属性值验证(XPO)
This lesson explains how to set rules for business classes and their properties. These rules are val ...
- XAF-在代码中实现属性值验证(EF)
This lesson explains how to set rules for business classes and their properties. These rules are val ...
- Model中设置表单验证方法
Model类里面定义$_validate属性支持的验证因子格式: 格式:array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间). 验证条件: (1)Model::EXISTS_TO_ ...
随机推荐
- SharePoint 如何使自己的网页自动跳转
SharePoint 如何使自己的网页自动跳转 SharePoint自动制作自己的网页跳的很easy,只有在页面上要添加一个Web部分--内容编辑器,对应的js代码就可以. ...
- Claris and XOR
Problem Description Claris loves bitwise operations very much, especially XOR, because it has many b ...
- C# 反射技术应用
反射(Reflection)是.NET中的重要机制,通过放射,可以在运行时获得.NET中每一个类型(包括类.结构.委托.接口和枚举等)的成员,包括方法.属性.事件,以及构造函数等.还可以获得每个成员的 ...
- crawler_Docker_解决用 JavaScript 框架开发的 Web 站点抓取
[转载,后续补上实践case] 有了 Docker,用 JavaScript 框架开发的 Web 站点也能很好地支持网络爬虫的内容抓取 [编者的话]Prerender 服务能够为网络爬虫提供预先渲染的 ...
- Swift得知——使用和分类功能(四)
Swift得知--使用和分类功能(四) 总结Swift该功能使用的总可分为七类 1 ---- 没有返回值,没有參数的函数 2 ---- 有參数和返回值的函数 3 ---- 使用元祖来返回多个值 4 - ...
- IntelliJ IDEA 开发scala
1.下载安装IntelliJ IDEA,并安装scala插件 我下载的是linux的13版本,linux版本是绿色版本,有一个启动的脚本,运行就可以了,也可以在linux建立快捷方式.windows的 ...
- VS2012使用XListCtrl
XListCtrl.强大ListCtrl.到现在,所有我曾经遇到过ListCtrl我们使用XListCtrl攻克. XListCtrl有什么可以支持? 变化column背景颜色.尺寸.线.制作chec ...
- Cocos2d-x数据持久-变更数据
当数据变化,参与SQL报表insert.update和delete声明.这项3个月SQL语句可以带参数. 详细过程的数据,例如,下面的变化看出.(1) 采用sqlite3_open开放式数据库功能.( ...
- CentOS修改用户密码方法
CentOS修改用户密码方法 CentOS修改用户密码方法 1. 普通用户 a. 获取超级用户root权限 命令:su或者su -或者su - root b. passwd 用户名 2. 超级用户 a ...
- 刚学unity3d,跟着仿作了flappy bird,记下一些琐碎的心得!
1.关于场景,即scene. 一个正常的游戏至少要有三个场景,即菜单(或者文件夹)场景.游戏关卡场景.游戏结束场景.它们一般统一放在project文件夹下scene文件夹(自己创建)中,方便管理. 1 ...