我希望能够确认输入的生日是18岁或以上。我搜索过并发现了很多关于此的帖子。但是,我不明白
1)为什么MS没有像其他验证一样将其构建成MVC3,如字符串,电子邮件,密码等。 2)为什么当我得到javascript以使日期正确验证时,其他不显眼的js不再起作用。
我希望在提交之前进行客户端验证,日期似乎不适用于此。其余的都是。
我错过了什么吗?
我在模型中尝试过的一些代码
#1) [Display(Name = "Date of Birth (must be at least 18) ")]
public DateTime Birthdate
{
get
{
if ((SelectedBMonth != "0") && (SelectedBday != "0") && (SelectedBYear != "0"))
return DateTime.Parse(SelectedBMonth + "/" + SelectedBday + "/" + SelectedBYear);
else
return DateTime.MinValue;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Birthdate.Date > DateTime.Today.AddYears(-18))
yield return new ValidationResult("You must be at least 18 years old to register", new[] { "Birthdate" });
}
#2)
[Required]
[CustomValidation(typeof(RegisterModel), "ValidateDOBDate")]
[DataType(DataType.Date)]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
public static ValidationResult ValidateDOBDate(DateTime DateOfBirthtovalidate) { if (DateOfBirthtovalidate.Date > DateTime.Now.AddYears(-18)) { return new ValidationResult("User should be atleast 18 years old."); } if (DateOfBirthtovalidate.Date < DateTime.Now.AddYears(-150)) { return new ValidationResult("Please put a valid date"); } return ValidationResult.Success; }
#3)
public class DateofBirthAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null || (DateTime)value < DateTime.Today.AddYears(-18))
return false;
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "dateofbirth"
};
}
}
[Required]
[Display(Name = "Date of Birth")]
[DateofBirth(ErrorMessage = "User must be at least 18")]
public DateTime Birthdate { get; set; }
View :
<div class="editor-label">
@Html.LabelFor(m => m.Birthdate)
</div>
<div class="editor-field">
@Html.TextBoxFor(x => x.Birthdate)
@Html.ValidationMessageFor(x => x.Birthdate)
</div>
Top of view before beginform:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MyScripts.js")" type="text/javascript"></script>
<script type="text/javascript">
// we add a custom jquery validation method
jQuery.validator.addMethod('greaterThan', function (value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params).val());
}
return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val()));
}, '');
// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('dateofbirth', {}, function (options) {
options.rules['greaterThan'] = true;
options.messages['greaterThan'] = options.message;
});
</script>
答案 0 :(得分:0)
这是一个动态验证,它取决于当前日期,并且在默认验证选项中不可用。
您可以轻松实现它,但不会生成客户端验证。
您还必须实现客户端javascript验证。
有关向ASP.NET MVC添加新验证的更多信息,请查看此ASP .Net MVC 3 unobtrusive custom client validation。