任何人都有C#MVC的出生日期验证属性? [英] Anyone got a Date of Birth Validation Attribute for C# MVC?

查看:76
本文介绍了任何人都有C#MVC的出生日期验证属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一定要在:-)之前写过这个

Someone must have written this before :-)

我需要一个出生日期的验证属性,用于检查该日期是否在特定范围内-即用户尚未输入尚未发生的日期或过去150年.

I need a validation attribute for date of birth that checks if the date is within a specific range - i.e. the user hasn't inputted a date that hasn't yet happened or is 150 years in the past.

感谢任何指针!

推荐答案

[DateOfBirth(MinAge = 0, MaxAge = 150)]
public DateTime DateOfBirth { get; set; }

// ...

public class DateOfBirthAttribute : ValidationAttribute
{
    public int MinAge { get; set; }
    public int MaxAge { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
            return true;

        var val = (DateTime)value;

        if (val.AddYears(MinAge) > DateTime.Now)
            return false;

        return (val.AddYears(MaxAge) > DateTime.Now);
    }
}

<罢工> 您可以使用内置的 Range属性:

You could use the built-in Range attribute:

[Range(typeof(DateTime),
       DateTime.Now.AddYears(-150).ToString("yyyy-MM-dd"),
       DateTime.Now.ToString("yyyy-MM-dd"),
       ErrorMessage = "Date of birth must be sane!")]
public DateTime DateOfBirth { get; set; }

这篇关于任何人都有C#MVC的出生日期验证属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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