在MVC 4使用模型根据出生日期年龄验证 [英] validate age according to date of birth using model in mvc 4

查看:377
本文介绍了在MVC 4使用模型根据出生日期年龄验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经报名表,其所含场出生日期。

I have registration form and its contain date of birth field.

使用日历日期选取器的输入值,以这个领域。

Using calender date picker its input the value to this field.

这些都是为这个字段中插入值的步骤

these are the steps to insert value for this field

第1步

第2步

第3步

所以其取值 DD / MM / YYYY 格式

这是我的模型类的出生日期字段的外观

This is appearance of date of birth field in my model class

[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }

这是在出生日期字段的外观我的视图文件

This is appearance of date of birth field in my view file

   <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>

我想要做的出生场的数据客户端验证。当输入提起显示错误信息不在此范围内的 100>年龄> 18

什么办法,我应该走?

推荐答案

那么既然你已经使用的数据的注解,为什么不自己做。
做到这一点:

Well since you are already using data annotations why not make your own. do this:

在您使用的DLL创建一个类或制作一个新的,至少以下code添加到它

create a class in an dll that you use or make a new one and at a minimum add the following code to it

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;
    }
}

然后在您的视图模型做到这一点:

then in your view model do this:

[MinimumAge(18)]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }

或你的网页,你不会有任何问题,你会用它捡起来的框架(S)。如果没有在你的类改变ErrorMessage属性,你会得到类似

or your web page you will have no issues as the framework(s) you use will pick it up. Without changing the ErrorMessage property in your class you will get something like

字段{0}是无效的。

{0}是由你给模型中的属性的属性名称或显示名称属性替换。

The {0} is replaced by the property name or display name attribute that you gave the property in your model.

希望它为你工作。

沃尔特
PS:请务必在控制器你做

Walter ps: make sure in the controller you do

if (ModelState.IsValid)
{
 ....
}

这篇关于在MVC 4使用模型根据出生日期年龄验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆