【问题标题】:Custom validation for Age must be greater than or equal to 18Age 的自定义验证必须大于或等于 18
【发布时间】:2023-03-31 18:48:01
【问题描述】:

我想对年龄大于或等于 18 的日期进行自定义验证。

任何一个想法都可以使用 mvc4 进行自定义验证吗?

如果有任何解决方案,请告诉我..

问候

【问题讨论】:

  • 我想从 datepicker 选择日期进行年龄验证...请让我知道任何人已经实现了自定义验证..

标签: asp.net-mvc-4 razor customvalidator model-validation


【解决方案1】:

只需使用Range 验证器:

[Range(18, int.MaxValue)]
public int Age { get; set; }

它在System.ComponentModel.DataAnnotations 命名空间中可用。

更新

要验证至少 18 年前的日期,您可以使用如下自定义验证属性:

public class Over18Attribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string message = String.Format("The {0} field is invalid.", validationContext.DisplayName ?? validationContext.MemberName);

        if (value == null)
            return new ValidationResult(message);

        DateTime date;
        try { date = Convert.ToDateTime(value); }
        catch (InvalidCastException e) { return new ValidationResult(message); }

        if (DateTime.Today.AddYears(-18) >= date)
            return ValidationResult.Success;
        else
            return new ValidationResult("You must be 18 years or older.");
    }
}

【讨论】:

  • 我可以在里面使用消息吗?
  • 从 datepicker 中满足年龄?
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2013-05-27
  • 1970-01-01
  • 2018-05-24
相关资源
最近更新 更多