验证年龄不低于18岁
本文关键字:18岁 不低于 验证 | 更新日期: 2023-09-27 18:28:30
如果用户未满18岁,如何显示错误消息?我使用以下代码,但它总是显示年龄无效,即使我输入的日期早于1995年。
DateTime dt = DateTime.Parse(dob_main.Text);
DateTime dt_now = DateTime.Now;
DateTime dt_18 = dt.AddYears(-18);
if (dt.Date >= dt_18.Date)
{
MessageBox.Show("Invalid Birth Day");
}
你应该尝试一下:
var age = GetAge(dt);
if(age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
int GetAge(DateTime bornDate)
{
DateTime today = DateTime.Today;
int age = today.Year - bornDate.Year;
if (bornDate > today.AddYears(-age))
age--;
return age;
}
题外话:考虑以这样一种方式命名变量,SO用户可以通过阅读来猜测变量的意图。dt
、dob_main
和dt_18
远非好名字。
DateTime dt = DateTime.Parse(dob_main.Text);
DateTime dt_now = DateTime.Now;
DateTime dt_18 = dt.AddYears(18); //here add years, not subtract
if (dt_18.Date >= dt_now.Date) //here you want to compare dt_now
{
MessageBox.Show("Invalid Birth Day");
}
DateTime bday = DateTime.Parse(dob_main.Text);
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if(age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
DateTime? BirthDate = DateTime.Parse(dob_main.Text);
if (BirthDate < DateTime.Now.AddYears(-18))
{
MessageBox.Show("Invalid Birth Day");
}
在解析日期后,只需使用这个就可以实现这一点:
private static bool GreaterThan18(DateTime bornIn)
{
return (bornIn.AddYears(18) >= DateTime.Now);
}
试试这个:
private static int CalculateAge(DateTime dateOfBirth)
{
int age = 0;
age = DateTime.Now.Year - dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
age = age - 1;
return age;
}
参考:https://naveed-ahmad.com/2010/01/08/calculating-age-from-date-of-birth-c/
试试这个:
DateTime birthDate = DateTime.Parse(dob_main.Text);
if (IsAgeLessThan18Years(birthDate))
{
MessageBox.Show("Invalid Birth Day");
}
bool IsAgeLessThan18Years(DateTime birthDate)
{
if (DateTime.Now.Year - birthDate.Year > 18)
{
return false;
}
else if (DateTime.Now.Year - birthDate.Year < 18)
{
return true;
}
else //if (DateTime.Now.Year - birthDate.Year == 18)
{
if (birthDate.DayOfYear < DateTime.Now.DayOfYear)
{
return false;
}
else if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
{
return true;
}
else //if (birthDate.DayOfYear == DateTime.Now.DayOfYear)
{
return false;
}
}
}
简单使用这种方式
DateTime BirthDate = DateTime.Parse(dob_main.Text);
DateTime CurrentDate = DateTime.Today;
int Age = CurrentDate.Year - BirthDate.Year;
if(Age < 18)
{
MessageBox.Show("Invalid Birth Day");
}