验证年龄 [英] validating date for age

查看:86
本文介绍了验证年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友.
我在asp.net页面中有一个文本按钮,用户将在其中输入日期.现在我希望根据用户输入的日期来计算他或她的年龄,
如果年龄是18岁或18岁以上,则只有在这种情况下,它才会允许用户,否则将显示味精无效日期"
预先感谢

hello friends.
i have a text button in asp.net page , user will enter date in it. now i want that on the basis of date enter by user we will calculate his or her age ,
and if age is 18 or more then 18 years ,only in that situation it will allow user otherwiseit will show msg ''invalid date''
thanks in advance

推荐答案

您可以在Button PostBack上进行验证,也可以创建CustomValidator来访问下面的代码.

You can either do the validation on your Button PostBack or create a CustomValidator to access the codebelow.

public bool IsLegalAge(string inputDate) 
{
            var bday = Convert.ToDateTime(inputDate);
            var ts = DateTime.Today - bday;
            var year = DateTime.MinValue.Add(ts).Year - 1;
            return year >= 18;
}



祝您好运!



Good luck!


在此操作的不同方法,请参见此处.
Different ways to do this discussed here.


尝试一下

try this

//In Page Load Or button click  whereever you want 

-------------------------------------------------------------
int k = CalculateAge(Convert.ToDateTime("10/25/1982"));

if (k>=18)
{
  //Valid
}

else
{
 //Invalid
}

-----------------------------------------------------------------  
  
//Function to return Date


 public static int CalculateAge(DateTime birthdate)
        {
            // get the difference in years
            int years = DateTime.Now.Year - birthdate.Year;
            // subtract another year if we''re before the
            // birth day in the current year
            if (DateTime.Now.Month < birthdate.Month || (DateTime.Now.Month == birthdate.Month && DateTime.Now.Day < birthdate.Day))
                years--;
            return years;
        }



//通过Javascript



//Via Javascript

<script type="text/javascript">
        function age() {
            alert("Hii");
    var birthDay = document.getElementById("TextBox1");
 var now = new Date()
 var b_split = birthDay.value.split(''/'');
 if(b_split.length==3){
   var birthDate = new Date(b_split[2], b_split[1]*1-1, b_split

[0]);
   var years = Math.floor((now.getTime() - birthDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
   if (years >= 18) {
       
//Your Condition
   }
   else {
//Your Condition

      
   }
 }
}
</script>


 //On Button
 <asp:Button ID="Button1" runat="server" Text="Button"  OnClientClick="javascript:return age();"  />


这篇关于验证年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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