在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返回类型.那么具体他们是有什么作用呢?它们的用法和区别是什么呢?通过资料书上的介绍和网上资料的查询,这里就来给大家列举和大致 ...
随机推荐
- Java for LeetCode 231 Power of Two
public boolean isPowerOfTwo(int n) { if(n<1) return false; while(n!=1){ if(n%2!=0) return false; ...
- ecshop修改后台访问地址
本文转自‘做个好男人’的博客. 打开data/config.php,找到define(’ADMIN_PATH’,’admin’),这里是定义后台目录的地方,把其中的admin换成你的后台自定义目录,如 ...
- maven加载本地oracle的JDBC驱动
转载自:http://blog.csdn.net/qicyt1812/article/details/13019933 由于oracle商业版权问题,maven不能通过中心资源库直接下载jar包,如果 ...
- 【leetcode】Reverse Linked List II (middle)
Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1-> ...
- PHP工厂模式的研究
工厂方法模式 把 创造者类 和要生产的 产品类 分离.创建者是一个工厂类,其定义了产品生产的类方法.一般情况下,创建者类的每个子类实例化一个相应的产品子类. 下面是单个产品的实现代码: <?ph ...
- CSS实现限制显示的字数,超出显示"..."
一.背景 在实际项目中,我们常常需要对某些页面的某些特定区域显示指定数量的内容,超出的内容显示"..."来进行美化页面,那么应该怎么做呢?今天就让我们来看看如何达到这一效果. 二. ...
- Cannot change version of project facet Dynamic Web Module to 3.0
背景描述: 最近在开发项目时,老是报错说:Project is not Dynamic Web Module 3.0.右击项目选择属性进行修改时出现以下错误: 这让我很是恼火,后来终于找到了万能的解决 ...
- google关于ssh key的解释(转)转的google的wiki的
SSH keys (简体中文) SSH 密钥对可以让您方便的登录到 SSH 服务器,而无需输入密码.由于您无需发送您的密码到网络中,SSH 密钥对被认为是更加安全的方式.再加上使用密码短语 ( ...
- 20145206《Java程序设计》第9周学习总结
20145206 <Java程序设计>第9周学习总结 教材学习内容总结 第十六章 整合数据库 JDBC是用于执行SQL的解决方案,开发人员使用JDBC的标准接口,数据库厂商则对接口进行操作 ...
- hdu 2602
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602 #include<cstdio> #include<iostream> ...