回到目录
之前的同事,也是我的哥们,问我下拉列表框是否可以支持验证,这个问题看似简单,但确实MVC里有为我们提供,所以,只能自己写个扩展了,即自己写一个attribute特性,让它继承ValidationAttribute,使它可以与其它MVC提供的验证一起使用.
在MVC的特性验证,很方便,很直接,它无论是在数据安全性上还是在页面表现上都做的不错,它的运行机制是这样的,前台表单验证规则有个名称,然后前台JS有对这个规则编写的代码,用来控制前台HTML标记的显示,而后台主要是生成验证规则和向前台参数赋值的。事实上,我们要知道的是,MVC验证不是简单的后台验证,它还有对前台页面的控制的JS部分,它一般被继承到了jquery.validate.min.js里了,如果我们要是自己开发一套验证规则,也需要自己的JS库与相配合。
C#部分:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class NotDefaultValueAttribute : ValidationAttribute, IClientValidatable { public string InputString { get; set; } public NotDefaultValueAttribute() { ErrorMessage = "请选其中一项"; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { ModelClientValidationRule rule = new ModelClientValidationRule { ValidationType = "notdefaultvalue", ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters["inputstring"] = InputString; yield return rule; } public override bool IsValid(object value) { if (value == null) return true; string inputString = (string)value; if (inputString.Contains(InputString)) { return false; } return true; } }
为viewmodel添加特性
public class TestModel { [Required] [Display(Name = "用户名")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "密码")] public string Password { get; set; } [Display(Name = "爱好")] [NotDefaultValue(InputString = "1")]/*如果用户选择为1,则验证不通过*/ public IEnumerable<SelectListItem> Liker { get; set; } }
在前面添加相对应的JS代码,建议将自定义的JS库放在一个单独的文件里,这样扩展性更强一些。
$.validator.addMethod('notdefaultvalue', function (value, element, param) { if (value == false) { return true; } if (value.indexOf(param) != -1) { return false; } else { return true; } }); $.validator.unobtrusive.adapters.addSingleVal('notdefaultvalue', 'inputstring');
OK,现在就可以运行我们的程序了,看看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7fe3D8mPd3z5WFvNlVx1dhxH0WDHVi/a71/HN5c38l/Tkyzaf1/f1/b//e346defxIfa3h1/PD/0XLTnR399/fIrcxxFgz1bv2gvcbm8mfW6pX1TrIrgs/M6q7bxzefj+8azzo8mNx6a60RFg13aRtE2P4oGu6BoigZxKJqiQRyKpmgQh6IpGsShaIoGcSiaokEciqZoEIeiKRrEoWiKBnEomqJBHEsU7RiCosH2zV60u0BG/yUAy1hijQawDEUD4lA0IA5FA+JQNCAORQPiUDQgDkUD4lA0IA5FA+JQNCAORQPiUDQgDkUD4lA0IA5FA+JQNCAORQPiUDQgjv8DvdLYNhuI/fcAAAAASUVORK5CYII=" alt="" />
怎么样,像这种扩展,我们还可以写很多,举一反三吧,呵呵!
回到目录