本文体验范围验证。与本文相关的包括:
MVC验证01-基础、远程验证
MVC验证02-自定义验证规则、邮件验证
MVC验证03-自定义验证规则、禁止输入某些值
当需要对字符串长度进行验证,可以用StringLength:
[StringLength(100, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = 6)]
当需要对数组范围进行验证,可以用Range:
[Range(0,5)]
如果需要对日期范围进行验证呢?
假设来验证日期,以当前日期为基准,介于当前日期和第七天之间的日期为有效,其它无效。
自定义验证特性,继承 ValidationAttribute 并实现IClientValidatable
重写基类ValidationAttribute的IsValid()方法,是为了服务端验证用的。
实现IClientValidatable接口方法,是为了在前端html元素增加某个属性,好让jquery侦测到。
展开using System; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcValidation.Extension { public class DayRangeAttribute : ValidationAttribute, IClientValidatable { private int _minDay; private int _maxDay; public DayRangeAttribute(int minDay, int maxDay) { if (minDay.CompareTo(maxDay) > -1) { throw new Exception("最小日期不能大于或等于最大日期"); } this._minDay = minDay; this._maxDay = maxDay; } public override bool IsValid(object value) { if (value == null) return true; var compareDate = value as DateTime?; if (compareDate.HasValue) { compareDate = compareDate.Value.Date; return compareDate.Value >= DateTime.Today.AddDays(_minDay).Date && compareDate.Value <= DateTime.Today.AddDays(_maxDay).Date; } return false; } public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "dayrange", //这里的dayrange最终会成为data-val-dayrange属性被jquery侦测到 ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; //这里了的min和max将会作为jquery验证扩展方法的参数 rule.ValidationParameters["min"] = _minDay; rule.ValidationParameters["max"] = _maxDay; yield return rule; } } }
注意:
■ ValidationType = "dayrange"中的dayrange必须小写,否则报错。
■ ValidationType = "dayrange"最终成为html元素的一个属性data-val-dayrange,从而能被jquery侦测辨别。
■ rule.ValidationParameters["min"]和rule.ValidationParameters["max"],min和max将作为参数供jquery扩展方法使用,当然也必须是小写。
把自定义验证特性打到View model上
[DayRange(0, 7)]验证当天到第七天之内的日期。
展开 public class RegisterModel { [Required] [StringLength(6, MinimumLength = 2)] //加 [Display(Name = "用户名")] //[Remote("CheckUserName","Validate", ErrorMessage = "远程验证用户名失败")] [NoInput("demo,jack",ErrorMessage = "不能使用此名称")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "邮件")] //[Email] public string Email { get; set; } [DayRange(0, 7)] [Display(Name = "上课时间")] public DateTime ClassDate { get; set; } [Required] [StringLength(100, ErrorMessage = "{0}栏位最少{2}个字,最多{1}个字", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "密码")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "确认密码")] [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "密码和确认密码不匹配。")] public string ConfirmPassword { get; set; }
扩展jquery验证jQuery.validator.dayrange.js
//扩展jquery验证方法
//第一个参数是前端输入的值
//第二个参数是html元素
//第三个参数是自定义验证特性DayRangeArribute中rule.ValidationParameters["min"]和rule.ValidationParameters["max"]的键值
jQuery.validator.addMethod(‘dayrange‘, function(value, element, param) {
if (!value) {
return false;
}
//value:1999/1/1
var valueDateParts = value.split(‘-‘);
var minDate = new Date();
var maxDate = new Date();
var now = new Date();
var dateValue = new Date(valueDateParts[2],
(valueDateParts[1] - 1),
valueDateParts[0],
now.getHours(),
now.getMinutes(),
(now.getSeconds() + 5));
minDate.setDate(minDate.getDate() - parseInt(param.min));
maxDate.setDate(maxDate.getDate() + parseInt(param.max));
return dateValue >= minDate && dateValue <= maxDate;
});
//第一个参数是jquery验证扩展方法名
//第二和第三个参数分别是最小或最大值
//第三个参数为DayRangeAttribute中ValidationType对应的值
jQuery.validator.unobtrusive.adapters.addMinMax(‘dayrange‘, ‘min‘, ‘max‘, ‘dayrange‘);
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Register.cshtml视图
展开@model MvcValidation.Models.RegisterModel @{ ViewBag.Title = "注册"; } <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>创建新帐户。</h2> </hgroup> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary() <fieldset> <legend>注册表单</legend> <ol> <li> @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName) </li> <li> @Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email) </li> <li> @Html.LabelFor(m => m.ClassDate) @Html.TextBoxFor(m => m.ClassDate) </li> <li> @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password) </li> <li> @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword) </li> </ol> <input type="submit" value="注册" /> </fieldset> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script src="~/Scripts/jQuery.validator.dayrange.js"></script> }
效果:
MVC验证04-自定义验证规则、日期范围验证,布布扣,bubuko.com