开发者

Anyone got a Date of Birth Validation Attribute for C# MVC?

Someone must have written this before :-)

I need a validation attrib开发者_运维技巧ute 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.

Thanks for any pointers!


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


I made a Validate class where I can validate data. In my class I have 2 methods for validating date of birth: 1 that takes a string parameter and the other takes a date parameter. Here is the basic method:

public static bool DateOfBirthDate(DateTime dtDOB) //assumes a valid date string
{
    int age = GetAge(dtDOB);
    if (age < 0 || age > 150) { return false; }
    return true;
}

Here is the full class:

using System;
using System.Collections.Generic;
using System.Text;

namespace YourNamespaceHere
{
    public class Validate
    {
        public static bool DateOfBirthString(string dob) //assumes a valid date string
        {
            DateTime dtDOB = DateTime.Parse(dob);
            return DateOfBirthDate(dtDOB);
        }

        public static bool DateOfBirthDate(DateTime dtDOB) //assumes a valid date
        {
            int age = GetAge(dtDOB);
            if (age < 0 || age > 150) { return false; }
            return true;
        }

        public static int GetAge(DateTime birthDate)
        {
            DateTime today = DateTime.Now;
            int age = today.Year - birthDate.Year;
            if (today.Month < birthDate.Month || (today.Month == birthDate.Month && today.Day < birthDate.Day)) { age--; }
            return age;
        }

    }
}

Here is how I'm calling the method in my Xamarin.Forms app:

bool valid = Validate.DateOfBirthDate(pickerDOB.Date);

Where pickerDOB is a date picker on my form. This makes it easy to call the validation methods from anywhere and validate a string or DateTime object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜