题
下面的代码工作正常服务器端而不是客户端.为什么?
当我提交表单时,控制权转到BeAValidDate函数以检查日期是否有效.有没有办法验证日期而无需使用Fluent验证进入服务器?
脚本
<script src="jquery-1.7.1.min.js" type="text/javascript"></script> <script src="jquery.validate.js" type="text/javascript"></script> <script src="jquery.validate.unobtrusive.js" type="text/javascript"></script>
模型
public class PersonValidator : AbstractValidator<Person> { public PersonValidator() { RuleFor(x => x.FromDate) .NotEmpty() .WithMessage("Date is required!") .Must(BeAValidDate) .WithMessage("Invalid Date"); } private bool BeAValidDate(String value) { DateTime date; return DateTime.TryParse(value,out date); } }
调节器
public class PersonController : Controller { public ActionResult Index() { return View(new Person { FromDate = DateTime.Now.AddDays(2).ToString()}); } [HttpPost] public ActionResult Index(Person p) { return View(p); } }
视图
@using (Html.BeginForm("Index","Person",FormMethod.Post)) { @Html.LabelFor(x => x.FromDate) @Html.EditorFor(x => x.FromDate) @Html.ValidationMessageFor(x => x.FromDate) <input type="submit" name="Submit" value="Submit" /> }
解决方法
使用更大然后或等于验证器的技巧.适合我.
Global.asax – 应用程序启动事件
FluentValidationModelValidatorProvider.Configure(x => { x.Add(typeof(GreaterThanOrEqualValidator),(Metadata,Context,rule,validator) => new LessThanOrEqualToFluentValidationPropertyValidator ( Metadata,validator ) ); });
模型
[Validator(typeof(MyviewmodelValidator))] public class Myviewmodel { [Display(Name = "Start date")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)] public DateTime StartDate { get; set; } [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)] public DateTime DateToCompareAgainst { get; set; } }
规则
public class MyviewmodelValidator : AbstractValidator<Myviewmodel> { public MyviewmodelValidator() { RuleFor(x => x.StartDate) .GreaterThanOrEqualTo(x => x.DateToCompareAgainst) .WithMessage("Invalid start date"); } }
FluentValidationPropertyValidator
public class GreaterThenOrEqualTo : FluentValidationPropertyValidator { public GreaterThenOrEqualTo(ModelMetadata Metadata,ControllerContext controllerContext,PropertyRule rule,IPropertyValidator validator) : base(Metadata,controllerContext,validator) { } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { if (!this.ShouldGenerateClientSideRules()) { yield break; } var validator = Validator as GreaterThanOrEqualValidator; var errorMessage = new MessageFormatter() .AppendPropertyName(this.Rule.GetDisplayName()) .BuildMessage(validator.ErrorMessageSource.GetString()); var rule = new ModelClientValidationRule{ ErrorMessage = errorMessage,ValidationType = "greaterthanorequaldate"}; rule.ValidationParameters["other"] = CompareAttribute.FormatPropertyForClientValidation( validator.MemberToCompare.Name); yield return rule; } }
控制器动作方法
public ActionResult Index() { var model = new Myviewmodel { StartDate = DateTime.Now.AddDays(2),DateToCompareAgainst = default(DateTime) //Default Date }; return View(model); } [HttpPost] public ActionResult Index(Practise.Areas.FluentVal.Models.Myviewmodel p) { return View(p); }
视图
@using (Html.BeginForm("Index",FormMethod.Post,new { id = "FormSubmit" })) { @Html.Hidden("DateToCompareAgainst",Model.DateToCompareAgainst); @Html.LabelFor(x => x.StartDate) @Html.EditorFor(x => x.StartDate) @Html.ValidationMessageFor(x => x.StartDate) <button type="submit"> OK</button> }
脚本
<script src="jquery-1.4.1.min.js" type="text/javascript"></script> <script src="jquery.validate.js" type="text/javascript"></script> <script src="jquery.validate.unobtrusive.js" type="text/javascript"></script> <script type="text/javascript"> (function ($) { $.validator.unobtrusive.adapters.add('greaterthanorequaldate',['other'],function (options) { var getModelPrefix = function (fieldName) { return fieldName.substr(0,fieldName.lastIndexOf(".") + 1); }; var appendModelPrefix = function (value,prefix) { if (value.indexOf("*.") === 0) { value = value.replace("*.",prefix); } return value; } var prefix = getModelPrefix(options.element.name),other = options.params.other,fullOtherName = appendModelPrefix(other,prefix),element = $(options.form).find(":input[name=" + fullOtherName + "]")[0]; options.rules['greaterthanorequaldate'] = element; if (options.message != null) { options.messages['greaterthanorequaldate'] = options.message; } });
$.validator.addMethod('greaterthanorequaldate',function (value,element,params) { var date = new Date(value); var dateToCompareAgainst = new Date($(params).val()); if (isNaN(date.getTime()) || isNaN(dateToCompareAgainst.getTime())) { return false; } return date >= dateToCompareAgainst; }); })(jQuery); </script>