首页 > 代码库 > TextBox控件只允许输入出生日期,并验证年龄不得小于18岁

TextBox控件只允许输入出生日期,并验证年龄不得小于18岁

1.Body tag

<form id="form1" runat="server">    <div>      <asp:Label ID="lblDob" runat="server" Text="Date of Birth :"></asp:Label>      <asp:TextBox ID="txtDob" runat="server" onblur="Validate();"></asp:TextBox><asp:Label ID="Label3" runat="server" Text="(mm/dd/yyyy)"></asp:Label>        <asp:RegularExpressionValidator ID="dateValRegex" runat="server" ControlToValidate="txtDob"            ErrorMessage="*Please Enter a valid date in the format (mm/dd/yyyy)" ValidationExpression="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"            ForeColor="Red"></asp:RegularExpressionValidator>    </div>    </form>
View Code


2.JavaScript 代码

 <script>        function Validate() {                var enteredValue = http://www.mamicode.com/document.getElementById(<%=txtDob.ClientID %>);                var enteredAge = getAge(enteredValue.value);                if (enteredAge < 18) {                    alert("you are too young");                    enteredValue.focus();                    return false;                }            }            function getAge(DOB) {                var today = new Date();                var birthDate = new Date(DOB);                var age = today.getFullYear() - birthDate.getFullYear();                var m = today.getMonth() - birthDate.getMonth();                if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {                    age--;                }                return age;            }        </script>
View Code

 

TextBox控件只允许输入出生日期,并验证年龄不得小于18岁