简体   繁体   English

使用 mvc 4 中的模型根据出生日期验证年龄

[英]validate age according to date of birth using model in 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这些是为此字段插入值的步骤

step 1第1步

在此处输入图片说明

step 2第2步

在此处输入图片说明

step 3第 3 步

在此处输入图片说明

so its taking values in dd/MM/yyyy format所以它以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>

I want to do client side validation for data of birth field .我想对出生字段的数据进行客户端验证。 show error message when input filed is not in this range 100>Age>18输入字段不在此范围内时显示错误消息100>Age>18

whats the approach I should take ?我应该采取什么方法?

Well since you are already using data annotations why not make your own.既然您已经在使用数据注释,为什么不自己做。 do this:做这个:

create a class in an dll that you use or make a new one and at a minimum add the following code to it在您使用的 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;
    }
}

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

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如果不更改类中的 ErrorMessage 属性,您将得到类似

The field "{0}" is not valid.字段“{0}”无效。

The {0} is replaced by the property name or display name attribute that you gave the property in your model. {0} 将替换为您在模型中为该属性指定的属性名称或显示名称属性。

Hope it works for you.希望对你有效。

Walter ps: make sure in the controller you do Walter ps:确保您在控制器中执行

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

I've improved on Walter's answer regarding making your own custom validation.我已经改进了 Walter 关于制作自己的自定义验证的答案。 I've added better error message support.我添加了更好的错误消息支持。 This will allow a better default error message and also allow you to enter your own with better string.Format support.这将允许更好的默认错误消息,并且还允许您使用更好的 string.Format 支持输入自己的错误消息。 I've also updated the naming schemes.我还更新了命名方案。 For instance you should add date to the beginning so that you and other developers know that this validation can only be used with DateTime variables similar to how the base StringLengthAttribute is named for strings.例如,您应该在开头添加日期,以便您和其他开发人员知道此验证只能与 DateTime 变量一起使用,类似于为字符串命名基本 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; }

a comment asks TroySteven if there is a way to allow null一条评论询问 TroySteven 是否有办法允许 null

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

Create an id for @Html.ValidationMessageFor and @Html.TextBoxFor, then use javascript to validate it.为@Html.ValidationMessageFor 和@Html.TextBoxFor 创建一个id,然后使用javascript 对其进行验证。 In your view do something like:在您看来,请执行以下操作:

@section scripts{
    <script>
      $(function () {
         if (document.getElementById("yourTextBoxID").value < 18){
             document.getElementById("yourValidationMessageID").value = "Can't be less than 18 years old :("
            }
       });
    </script>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM