C# 使用MVC4中的模型根据出生日期验证年龄
我有登记表及其包含出生日期字段 使用日历日期选择器将其值输入到此字段 以下是为该字段插入值的步骤 第一步 步骤2 步骤3 因此它采用dd/MM/yyyy格式的值 这是my模型类中出生日期字段的外观C# 使用MVC4中的模型根据出生日期验证年龄,c#,jquery,asp.net,asp.net-mvc-4,razor,C#,Jquery,Asp.net,Asp.net Mvc 4,Razor,我有登记表及其包含出生日期字段 使用日历日期选择器将其值输入到此字段 以下是为该字段插入值的步骤 第一步 步骤2 步骤3 因此它采用dd/MM/yyyy格式的值 这是my模型类中出生日期字段的外观 [DisplayName("Date of Birth")] [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nu
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }
[DisplayName(“出生日期”)]
[DataType(DataType.Date),DisplayFormat(DataFormatString=“{0:dd/MM/yyyy}”,ApplyFormatInEditMode=true]
公共可为空的出生日期{get;set;}
这是我的查看文件中出生日期字段的外观
<div class="form-group">
<div class="editor-label">
@Html.LabelFor(model => model.Date_of_Birth)
@Html.Label("*", new { id="star" , @class = "requiredFiledCol" })
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Date_of_Birth, "{0:dd/MM/yyyy}", new { @class = "form-control datepicker", placeholder = "DD/MM/YYYY" , maxlength="100" })
@Html.ValidationMessageFor(model => model.Date_of_Birth)
</div>
</div>
@LabelFor(model=>model.Date出生日期)
@Html.Label(“*”,新的{id=“star”,@class=“requiredFiledCol”})
@Html.TextBoxFor(model=>model.Date\u of_Birth,“{0:dd/MM/yyyy}”,new{@class=“form control datepicker”,placeholder=“dd/MM/yyyy”,maxlength=“100”})
@Html.ValidationMessageFor(model=>model.Date出生日期)
我想对出生字段的数据进行客户端验证。当输入字段不在此范围内时显示错误消息100>Age>18
我应该采取什么方法?为@Html.ValidationMessageFor和@Html.TextBoxFor创建一个id,然后使用javascript对其进行验证。在您看来,请执行以下操作:
@section scripts{
<script>
$(function () {
if (document.getElementById("yourTextBoxID").value < 18){
document.getElementById("yourValidationMessageID").value = "Can't be less than 18 years old :("
}
});
</script>
}
@节脚本{
$(函数(){
if(document.getElementById(“yourTextBoxID”).value<18){
document.getElementById(“yourValidationMessageID”).value=“不能少于18岁:(”
}
});
}
既然您已经在使用数据注释,为什么不创建自己的注释呢。
这样做:
在您使用的dll中创建一个类或创建一个新类,并至少向其中添加以下代码
public class MinimumAgeAttribute: ValidationAttribute
{
int _minimumAge;
public MinimumAgeAttribute(int minimumAge)
{
_minimumAge = minimumAge;
}
public override bool IsValid(object value)
{
DateTime date;
if (DateTime.TryParse(value.ToString(),out date))
{
return date.AddYears(_minimumAge) < DateTime.Now;
}
return false;
}
}
我改进了Walter关于自定义验证的回答。我添加了更好的错误消息支持。这将允许更好的默认错误消息,也允许您使用更好的字符串格式支持输入自己的错误消息。我还更新了命名方案。例如,您应该将日期添加到开头,以便您和其他人er开发人员知道,此验证只能与日期时间变量一起使用,类似于基本StringLengthAttribute为字符串命名的方式
public class DateMinimumAgeAttribute : ValidationAttribute
{
public DateMinimumAgeAttribute(int minimumAge)
{
MinimumAge = minimumAge;
ErrorMessage = "{0} must be someone at least {1} years of age";
}
public override bool IsValid(object value)
{
DateTime date;
if ((value != null && DateTime.TryParse(value.ToString(), out date)))
{
return date.AddYears(MinimumAge) < DateTime.Now;
}
return false;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, MinimumAge);
}
public int MinimumAge { get; }
}
[DateMinimumAge(18, ErrorMessage="{0} must be someone at least {1} years of age")]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }
公共类DateMinimumAgeAttribute:ValidationAttribute
{
公共日期最小值属性(int最小值)
{
最小值=最小值;
ErrorMessage=“{0}必须是至少{1}岁的人”;
}
公共覆盖布尔值有效(对象值)
{
日期时间日期;
if((value!=null&&DateTime.TryParse(value.ToString(),out date)))
{
返回日期.AddYears(MinimumAge)public override bool IsValid(object value)
{
DateTime date;
if (value == null) //you can just add this condition
{
return true;
}
if ((value != null && DateTime.TryParse(value, out date)))
{
return date.AddYears(MinimumAge) < DateTime.Now;
}
return false;
}
public override bool有效(对象值)
{
日期时间日期;
if(value==null)//您可以添加这个条件
{
返回true;
}
if((value!=null&&DateTime.TryParse(value,out-date)))
{
返回日期.AddYears(MinimumAge)
没有现成的方法可以做到这一点。您需要编写自己的验证属性并实现IClientValidable
。这提供了一个很好的指导。旁注:您没有使用EditorFor()
生成HTML5日期选择器so[DataType(DataType.Date)]
和ApplyFormatInEditMode=true
不是必需的(它们仅适用于EditorFor()
)我希望您正在通过javascript初始化日期选择器
。然后您将有几个选项来设置开始日期
和结束日期
,这样就不用担心验证了,您就可以呈现datepicker@Chathz,根据今天的日期计算控制器中允许的最小和最大日期,然后传递它们到视图(使用视图模型或ViewBag
属性,然后设置日期选择器minDate
和maxDate
选项-例如,{…,minDate:@model.MiinDate,…}`但这不会给您服务器端验证,因此您需要在POST方法中再次检查并添加ModelState.Errors
asappropriate@Chathz,您还可以使用数字偏移量指定minDate
和MaxDate
值,例如{minDate:-20,MaxDate:+1M+10D}
`这看起来是答案,您知道如何添加自定义错误消息吗?是的,只需以与MinimumAgeAttribute继承自ValidationAttribute相同的数据注释方式添加它。您只需通过资源或硬编码字符串值使用.net方式添加它。这似乎可行,但不允许空[出生日期]即使模型说可以为NULL。它在控制器的ModelState.IsValid部分返回false。是否有方法允许NULL作为true传递给ModelState.IsValid?
public class DateMinimumAgeAttribute : ValidationAttribute
{
public DateMinimumAgeAttribute(int minimumAge)
{
MinimumAge = minimumAge;
ErrorMessage = "{0} must be someone at least {1} years of age";
}
public override bool IsValid(object value)
{
DateTime date;
if ((value != null && DateTime.TryParse(value.ToString(), out date)))
{
return date.AddYears(MinimumAge) < DateTime.Now;
}
return false;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, MinimumAge);
}
public int MinimumAge { get; }
}
[DateMinimumAge(18, ErrorMessage="{0} must be someone at least {1} years of age")]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }
public override bool IsValid(object value)
{
DateTime date;
if (value == null) //you can just add this condition
{
return true;
}
if ((value != null && DateTime.TryParse(value, out date)))
{
return date.AddYears(MinimumAge) < DateTime.Now;
}
return false;
}