开发它的原因:
之前的同事,也是我的哥们,问我下拉列表框是否可以支持验证,这个问题看似简单,但确实MVC里有为我们提供,所以,只能自己写个扩展了,即自己写一个attribute特性,让它继承ValidationAttribute,使它可以与其它MVC提供的验证一起使用.
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,则验证不通过*/
public IEnumerable<SelectListItem> Liker { get; set; }
}
在前面添加相对应的JS代码,建议将自定义的JS库放在一个单独的文件里,这样扩展性更强一些。
$.validator.addMethod('notdefaultvalue', function (value, element, param) {
if (value == false) {
return true;
}
if (value.indexOf(param) != -) {
return false;
}
else {
return true;
}
});
$.validator.unobtrusive.adapters.addSingleVal('notdefaultvalue', 'inputstring');
OK,现在就可以运行我们的程序了,看看效果吧
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZsAAAEeCAIAAADThy/EAAAOn0lEQVR4nO3dPW7bWhqAYW0oyRZceA8pkg14DWkEZA0GUgVImSJdigDeQIpb5AK3nS1kC5qCtkyRh4eHFH8/PQ++wqYoisnY7xxSmszhBBDFYe0TAJiMogFxKBoQh6IBcSgaEIeiAXEoGhCHonX79/vx4eHh4fGpd8+nx8IdgVktU7TnNqQdv/874Us9PTbS8u/348iXUDTYmx0X7ekx8eTWxuqlR8VG0WBvlr/qnOq3vzpOo2jPEXrd+tLSMa+naLA3WyraxUquvkP1lPqS7mJLLWEv289Ja21IH6/jJJpnUn9i/XmKBtuwlaKlrkufm3FZr2pjR9Fej9J67vkFm09N9S9VtNRjLwdVNNiGoqL97wqtgyV/+5sbaxd81Zftm22Jq87nXR8fj/Wl3ONj7d7ac5eaDXt8OrUvWetXna2zuHj51p/pmr8xYLTSopXsViZVtOTa6ByM15VX+1I0cTX5+PTv9yppVdCeajVq3xp7fbD1WCurnQs4azTYhj0UrXKOysVVYHuPc5yqtdnjU/0lFQ1C20bRSt9VrFesXbTakV8KVF/k1d9SaN5Ve3w6ta9I62eVfGc1+2cClreNoqVWaa97NB+rHrlcNj0+NaJz8cG0ROtSS8H0Siz1co285XsHLGUrRTu1m9H8REYzdBdPuLhb9vK05GqrecTkajH9ium01h6xSoN1LV80gLkoGhCHogFxKBoQh6IBcSgaEIeiAXEoGhCHogFxKBoQh6IBcSgaEIeiAXEoGhCHogFxKBoQh6IBcSgaEIeiAXEoGhDHpov28PAw4W5AeAsVLfF/Gncp88SSg195ekAMyxWt8Nuh7RuaSCCwLRZt9HFKjgAEtteinRdiJY0DbsTm7qMNWqM1NsoZ3LgtrtEG3UerP+vKkwT2botFKz/OScuAmp1ddZYf88oTBvZoZ2u08z4PqbcFBh0EiGeXRevdWdHgNi1R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RVM0iEPRFA3iUDRFgzgUTdEgDkVTNIhD0RQN4lA0RYM4FE3RIA5FUzSIQ9EUDeLYRtF+fnp3OHvz+ef6CVM02KMNFO3np3evFfvx+e3h49f1E6ZosEerF+3H57eHd8cftS1fPl98O838On76pmgQ3dpFu1igzTdfPh7eKxqEt3bRvr4/vP30K7n9cDgcDu+OP8532V6vRl8evbzp9uXj6824c79+fH57qLtYD6aPo2iwV1st2vOl4pt3H96/e/vp15/f3z68xOjr+8OHL/+9BquK14/Pb1+r9Ov4pnElm1ijpY+jaLBjWy9a+9FvHw6X0su03qJlj6NosEtrF+3np3fdd7haS63mWqxVqOdDFazROo+jaLBfaxftz5ePh8bHNV7f60wV7fe3D8mPd3z5WFvNlVx1dhxH0WDHVi/a71/HN5c38l/Tkyzaf1/f1/b//e346defxIfa3h1/PD/0XLTnR399/fIrcxxFgz1bv2gvcbm8mfW6pX1TrIrgs/M6q7bxzefj+8azzo8mNx6a60RFg13aRtE2P4oGu6BoigZxKJqiQRyKpmgQh6IpGsShaIoGcSiaokEciqZoEIeiKRrEoWiKBnEomqJBHEsU7RiCosH2zV60u0BG/yUAy1hijQawDEUD4lA0IA5FA+JQNCAORQPiUDQgDkUD4lA0IA5FA+JQNCAORQPiUDQgDkUD4lA0IA5FA+JQNCAORQPiUDQgjv8DvdLYNhuI/fcAAAAASUVORK5CYII=" alt="" />
怎么样,像这种扩展,我们还可以写很多,举一反三吧,呵呵!