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

更多细节请参考如下链接:

http://mvcdiary.com/2013/02/28/conditional-required-validation-or-field-mandatory-depends-on-another-field-mvc-4/

在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证的更多相关文章

  1. 在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证

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

  2. 在.Net MVC中自定义ValidationAttribute标签对Model中的属性做验证

    写一个继承与ValidationAttribute类的自定义的验证方法 MVC中传递数据时,大多数都会用Model承载数据,并且在传到控制器后,对Model进行一系列的验证. 我平时经常使用的判断方法 ...

  3. Asp.net mvc + .net ef database first 或 model first 时如何添加验证特性

    今天有个同事问到,在使用Entity Framework 的Database frist或model first时,怎么在model上添加验证的特性? 因为此时的Model是是VS 工具怎么生成的,直 ...

  4. CompareValues标签对Model中的属性进行验证

    在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证   在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个 ...

  5. 返璞归真 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 ...

  6. mvc中动态给一个Model类的属性设置验证

    原文:mvc中动态给一个Model类的属性设置验证 在mvc中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...

  7. 总结ASP.NET MVC Web Application中将数据显示到View中的几种方式

    当我们用ASP.NET MVC开发Web应用程序的时候,我们都是将需要呈现的数据通过"Controllers"传输到"View"当中,怎么去实现,下面我介绍一下 ...

  8. Asp.Net MVC 从客户端<a href="http://www....")中检测到有潜在危险的 Request.Form 值

    Asp.Net MVC应用程序, Framework4.0: 则需要在webconfig文件的 <system.web> 配置节中加上 <httpRuntime requestVal ...

  9. asp.net mvc 3.0 知识点整理 ----- (2).Controller中几种Action返回类型对比

    通过学习,我们可以发现,在Controller中提供了很多不同的Action返回类型.那么具体他们是有什么作用呢?它们的用法和区别是什么呢?通过资料书上的介绍和网上资料的查询,这里就来给大家列举和大致 ...

随机推荐

  1. Smallest Rectangle Enclosing Black Pixels

    An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black ...

  2. Unity3d 换装Avatar系统

    原理就是用新造的部件和角色的骨骼进行重新对接. demo的使用方法: PartIdx设置要换那个部件[0,4],一共5个部件 EquipIdx设置要更换部件的装备索引[0,1],具体看我的Change ...

  3. 压测 apache ab 初探

    2015年10月30日 14:58:34 ab是apache自带的压测命令, 在其bin目录下边, 不仅可以压测Apache, 也可以测nginx或其他服务器 可以模拟上传post值 (-p, 与下边 ...

  4. Linux下常用的硬件信息查看命令

    1.查看CPU型号,这里为了方便查看结合管道符用grep进行了匹配,当然只需要前面的命令也可以,命令如下: cat /proc/cpuinfo | grep "model name" ...

  5. cxGrid的使用方法

    来源 http://www.cnblogs.com/djcsch2001/archive/2010/07/19/1780573.html   1.  去掉GroupBy栏 cxGrid1DBTable ...

  6. 6.SpringMVC注解启用

    SpringMVC注解可以帮助我们快速地注入 属性和参数 提高开发效率. 由于 有相当一部分人讨厌xml配置方式 注解可以覆盖 xml则不能 使用注解比xml规范化,因为很多注解都是java的规范的范 ...

  7. google 语音api

    mdeia.Source = new Uri("http://translate.google.cn/translate_tts?ie=UTF-8&q=你好&tl=zh-CN ...

  8. [Android] ListView中如何让onClick和onItemClick事件共存

    ListView中如何使用Button,让onClick和onItemClick事件共存 假如ListView的一条记录包含一个TextView文本框,一个Button按钮,怎样能让点击按钮有事件响应 ...

  9. VC++ 模块与资源分离

    在一些开发过程中,需要模块支持中英文语言切换,比较好的实现方式是从模块中将资源分离出来,做成中英文两个资源dll,根据需要加载不同的dll从而实现切换不同的语言显示. 新建一个资源dll文件,选择Wi ...

  10. git remote 相关用法

    为了便于管理,Git要求每个远程主机都必须指定一个主机名.git remote  命令就用于管理主机名. 不带选项的时候,git remote命令列出所有远程主机. $ git remote orig ...