在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现RequiredIf标签对Model中的属性进行验证
具体场景为:某一属性是否允许为null的验证,要根据另一个属性值是否为true来判断
代码如下所示:
1):后台代码
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; } public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
} protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
if (field != null)
{
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if (Object.Equals(dependentValue, TargetValue))
{
if (!innerAttribute.IsValid(value))
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
} public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
}; string depProp = BuildDependentPropertyId(metadata, context as ViewContext); // find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower(); rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue); yield return rule;
} private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
} }
2):前台代码
$.validator.addMethod('requiredif', function (value, element, parameters) {
var id = '#' + parameters['dependentproperty']; // get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
targetvalue = (targetvalue == null ? '' : targetvalue).toString(); // get the actual value of the target control
// note - this probably needs to cater for more
// control types, e.g. radios
var control = $(id);
if (control == null || control.length == 0) { // if control is null, the control is a checkbox or a radio
control = $("[name='" + parameters['dependentproperty'] + "']:checked");
}
var controltype = control.attr('type');
var actualvalue =
(controltype === 'checkbox' || controltype === 'radio') ?
control.val() != "" ? control.val() : control.prop('checked').toString() :
control.val(); // if the condition is true, reuse the existing
// required field validator functionality
if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
return $.validator.methods.required.call(
this, value, element, parameters); return true;
}); $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'targetvalue'], function (options) {
options.rules['requiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['requiredif'] = options.message;
});
将标签RequiredIf添加到对应的属性上
【注:第一个参数为相关联的属性名,第二个参数表示相关联属性值(相关联属性值=第二个参数时,再对此属性进行验证),第三个参数为错误提示信息】
public class EricSunModel
{
public bool ContainsDangerousGoods { get; set; } [RequiredIf("ContainsDangerousGoods", true, ErrorMessage = "Please enter UN Number")]
[Display(Name = "UN Number")]
public string UNNumber { get; set; }
}
更多细节请参考如下链接:
在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证的更多相关文章
- 在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个中两个属性值的比较验证 具体应用场景为:要对两个属性值的大小进行验证 代码如下所示: /// ...
- 在.Net MVC中自定义ValidationAttribute标签对Model中的属性做验证
写一个继承与ValidationAttribute类的自定义的验证方法 MVC中传递数据时,大多数都会用Model承载数据,并且在传到控制器后,对Model进行一系列的验证. 我平时经常使用的判断方法 ...
- Asp.net mvc + .net ef database first 或 model first 时如何添加验证特性
今天有个同事问到,在使用Entity Framework 的Database frist或model first时,怎么在model上添加验证的特性? 因为此时的Model是是VS 工具怎么生成的,直 ...
- CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证 在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个 ...
- 返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model
原文:返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model [索引页][源码下载] 返璞归真 asp.net mvc (8) - asp.net mvc ...
- mvc中动态给一个Model类的属性设置验证
原文:mvc中动态给一个Model类的属性设置验证 在mvc中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...
- 总结ASP.NET MVC Web Application中将数据显示到View中的几种方式
当我们用ASP.NET MVC开发Web应用程序的时候,我们都是将需要呈现的数据通过"Controllers"传输到"View"当中,怎么去实现,下面我介绍一下 ...
- Asp.Net MVC 从客户端<a href="http://www....")中检测到有潜在危险的 Request.Form 值
Asp.Net MVC应用程序, Framework4.0: 则需要在webconfig文件的 <system.web> 配置节中加上 <httpRuntime requestVal ...
- asp.net mvc 3.0 知识点整理 ----- (2).Controller中几种Action返回类型对比
通过学习,我们可以发现,在Controller中提供了很多不同的Action返回类型.那么具体他们是有什么作用呢?它们的用法和区别是什么呢?通过资料书上的介绍和网上资料的查询,这里就来给大家列举和大致 ...
随机推荐
- poj 2488
http://poj.org/problem?id=2488 题意:就是让马把棋盘都走完,每一个点都要走到,出口就是a,b. #include <stdio.h> #include < ...
- liunux mysql MySQL表名不区分大小写的设置方法
原来Linux下的MySQL默认是区分表名大小写的,通过如下设置,可以让MySQL不区分表名大小写:1.用root登录,修改 /etc/my.cnf:2.在[mysqld]节点下,加入一行: lowe ...
- perform
public class ArgsTest { private List <Object> args; private ArgsTestCheckPoint checkPoint; pub ...
- Java for LeetCode 217 Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return t ...
- Django~queries
API queries create, retrieve, update and delete
- pgbouncer介绍
一.Pgbouncer 的介绍 Pgbouncer是一个针对PostgreSQL数据库的轻量级连接池,任何目标应用都可以把 pgbouncer 当作一个 PostgreSQL 服务器来连接,然后pgb ...
- ant使用指南详细入门教程
这篇文章主要介绍了ant使用指南详细入门教程,本文详细的讲解了安装.验证安装.使用方法.使用实例.ant命令等内容,需要的朋友可以参考下 一.概述 ant 是一个将软件编译.测试.部署等步骤联系在一起 ...
- dropdownlist 动态添加
this.DropDownList1.Items.Insert(0,new ListItem("","")); this.Drop ...
- iOS应用架构谈(二):View层的组织和调用方案(上)
OS客户端应用架构看似简单,但实际上要考虑的事情不少.本文作者将以系列文章的形式来回答iOS应用架构中的种种问题,本文是其中的第二篇,主要讲View层的组织和调用方案.上篇主要讲View层的代码结构. ...
- 电脑不能浏览网页but能登录qq,解决方案总结
电脑能登录qq,但是不能浏览网页,解决方法总结 [注]:仅供参考,属个人经验 今天早晨起来,电脑突然只能登录qq,不能上网了,从来没有遇到这种问题的我开始各种百度方法,各种尝试,最终成功解决了问题 首 ...