自定义验证在服务器端有效,但在客户端无效
Custom validation works server side but not client side asp mvc 5
我有一个自定义的验证类来验证日期。它在服务器端工作,但在客户端不工作。我无法触发jquery方法来进行检查。我想我可能有什么东西与适配器或验证器连接不正确。P.S.我可以获得非自定义客户端验证(例如[必需]),只是不能获得我的自定义验证
查看模型
public class HomePageViewModel
{
[Required]
public string SearchQuery { get; set; }
[DisplayName("Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[ClassDate(ErrorMessage = "Class date must be today or later.")]
public DateTime ClassDate { get; set; }
}
验证类。
public class ClassDateAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) // ok, just use todays date day
{
return true;
}
DateTime toValidate = (DateTime) value;
if (toValidate.Day < DateTime.Now.Day) // if they are looking for classes in the past
{
return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
ControllerContext context)
{
var classDateRule = new ModelClientValidationRule();
classDateRule.ErrorMessage = "test error message";
classDateRule.ValidationType = "classdate";
yield return classDateRule;
}
}
Javascript代码。
$(function () {
$(".datefield").datepicker();
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = (month) + "/" + (day) + "/" + now.getFullYear();
$('.datefield').val(today);
$.validator.unobtrusive.adapters.addSingleVal("classdate");
$.validator.addMethod("classdate", function(value) {
if (value) {
//do something to test date here
//if date is today or later
return true;
}
return false;
});
});
这是我认为的要素。
@Html.TextBoxFor(model => model.ClassDate, new { @class = "datefield form-control", @id = "ClassDate", @type = "date", name = "ClassDate" })
@Html.ValidationMessageFor(model => model.ClassDate, "", new { @class = "text-danger" })
没有获得客户端验证的主要问题是使用$.validator.unobtrusive.adapters.addSingleVal("classdate");
。addSingleVal()
用于针对模型中的另一个属性进行验证。它需要是$.validator.unobtrusive.adapters.addBool("classdate");
由于您使用的是jQueryUI日期选择器,因此可以防止使用选择小于今天日期的日期
$(.datefield).datepicker({
minDate: 0
});
你们很多人在这里的代码毫无意义(见下面的旁注),应该是类似的东西
属性定义
[DisplayName("Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
[NotLessThanToday]
public DateTime ClassDate { get; set; }
验证属性
public class NotLessThanTodayAttribute : ValidationAttribute, IClientValidatable
{
private const string _DefaultErrorMessage = "The property {0} cannot be less than todays date";
public NotLessThanTodayAttribute() : base(_DefaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return ValidationResult.Success; // ??
}
DateTime date = DateTime.Today;
if (DateTime.TryParse((string)value, out date))
{
if (date < DateTime.Today)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
else
{
// not a valid date
}
return base.IsValid(value, validationContext);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "notlessthantoday"
};
return new[] { clientValidationRule };
}
}
编写脚本
$.validator.addMethod("notlessthantoday", function (value, element, params) {
if (!this.optional(element)) {
var date = new Date(value);
var today = new Date();
return date > today;
}
return true; // ??
});
$.validator.unobtrusive.adapters.addBool("notlessthantoday");
纸币
ApplyFormatInEditMode = true
与CCD_ 5和CCD_浏览器HTML5日期选择器。这里没有必要,如果你需要的话使用它,格式字符串需要是"{0:yyyy-MM-dd}"
(ISO格式)- 您当前的验证属性仅在日期为天时才进行检查比今天少。
if (toValidate.Day < DateTime.Now.Day)
意味着1/1/2016
是有效的(1
小于24
) - 脚本
var now = new Date(); ..... $('.datefield').val(today);
毫无意义,并覆盖模型中的值(用户输入日期,您发布并返回视图,您的代码会重置日期回到今天的价值!)。如果要显示今天的日期,则在将值传递给视图之前,在模型中设置该值(model.ClassDate = Datetime.Today;
) - 您可以在辅助对象中设置(或尝试)以下属性:
@id="ClassDate", @type="date", name="ClassDate"
。html助手无论如何都将CCD_ 15属性设置为CCD_。这个type="date"
不是必需的(用于呈现浏览器HTML5datepicker)并设置name
属性什么都没有(幸运的是,它不起作用,因为你试图给予它如果名称不是"ClassDate",则绑定将失败)
document.ready…
1) 在加载整个网页后执行。
2) 通常,用于初始化dom元素上的事件(如.click、.change、.select)。这很有意义,因为您通常不能将事件附加到尚未加载的dom元素。
3) 通常,函数不会进入document.ready。这是有道理的,因为函数通常由事件调用。
当然,任何事情都有例外,但这些都是很好的经验法则。
相关文章:
- 客户端服务器REST API captcha实现
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- 如何使用Socket.io将命令从客户端发送到服务器
- 如何轻松地将服务器端变量从Java代码转移到客户端代码
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 从客户端获取修改后的对象,并将其与服务器上的原始对象组合
- 如何将我的javascript库公开给其他客户端使用
- 是否可以使用JavaScript/AAJAX在客户端创建一个文件
- 如何使用Javascript客户端对象模型检索Sharepoint 2010列表项权限
- 返回/从Twit's客户端.get
- 将客户端特定的日期格式返回到服务器MVC4
- MobileFirst:在客户端运行计时器作业-最佳选项
- 标签客户端的设置值
- 我的客户端选项是什么
- 仅在某些客户端上无效的 Web 服务调用
- 自定义验证在服务器端有效,但在客户端无效
- 客户端脚本生成验证的无效HTML
- 客户端位置检测在Safari桌面上有效,但在Safari手机上无效
- ASP服务器端验证显示无效,客户端验证显示有效
- 使用JS客户端使Google Drive的访问令牌无效