簡體   English   中英

使用 mvc 4 中的模型根據出生日期驗證年齡

[英]validate age according to date of birth using model in mvc 4

我有登記表,其中包含出生日期字段。

使用日歷日期選擇器輸入該字段的值。

這些是為此字段插入值的步驟

第1步

在此處輸入圖片說明

第2步

在此處輸入圖片說明

第 3 步

在此處輸入圖片說明

所以它以dd/MM/yyyy格式取值

這是我的模型類中出生日期字段的出現

[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { 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>

我想對出生字段的數據進行客戶端驗證。 輸入字段不在此范圍內時顯示錯誤消息100>Age>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;
    }
}

然后在您的視圖模型中執行以下操作:

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

或者您的網頁,您將沒有問題,因為您使用的框架會選擇它。 如果不更改類中的 ErrorMessage 屬性,您將得到類似

字段“{0}”無效。

{0} 將替換為您在模型中為該屬性指定的屬性名稱或顯示名稱屬性。

希望對你有效。

Walter ps:確保您在控制器中執行

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

我已經改進了 Walter 關於制作自己的自定義驗證的答案。 我添加了更好的錯誤消息支持。 這將允許更好的默認錯誤消息,並且還允許您使用更好的 string.Format 支持輸入自己的錯誤消息。 我還更新了命名方案。 例如,您應該在開頭添加日期,以便您和其他開發人員知道此驗證只能與 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; }

一條評論詢問 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;
}

為@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>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM