我希望能够验证输入的生日是否为 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>