Sunday, November 6, 2011

How to validate the birth date with javascript - Integer, Length and next focus.

Sometime, we are vulnerable to check the user input and client side validation is better than server side in that circumstances. This example show you how to check the user input for Birth Date.

Validating Birth Date with Javascript


Here is the javascript to put into <head> tag.

<script type="text/javascript">
    function OnKeyUpCheck(obj, n, e) {
        var unicode = e.keyCode ? e.keyCode : e.charCode
        var ch;
        var str = obj.value;
        if (str.length == 0) return true;
        for (var i = 0; i < str.length; i++) {
            ch = str.substring(i, i + 1);
            if ((ch < "0") || (ch > "9")) {
                alert("INVALID CHARECTER 0-9");
                obj.value = '';
            }
        }
        if (obj.value.length == obj.maxLength) {
            if ((unicode > 47) && (unicode < 128)) {
                n.focus();
            }
        }
    }
</script>

Add the below snippet to <form> tag.

<form id="form1" runat="server">
    <asp:Label ID="Label4" runat="server" >Birthdate(DD/MM/YYYY)</asp:Label>
    &nbsp;<asp:TextBox ID="txtDD" runat="server" MaxLength="2" Width="41px"
        AutoCompleteType="Disabled"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtDD"
        Display="Dynamic" ErrorMessage="*" ValidationGroup="Empty"
        ForeColor="Red"></asp:RequiredFieldValidator>
    <asp:TextBox ID="txtMM" runat="server" MaxLength="2" Width="41px"
        AutoCompleteType="Disabled"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtMM"
        Display="Dynamic" ErrorMessage="*" ValidationGroup="Empty"
        ForeColor="Red"></asp:RequiredFieldValidator>
    <asp:TextBox ID="txtYY" runat="server" MaxLength="4" Width="56px"
        AutoCompleteType="Disabled"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtYY"
        Display="Dynamic" ErrorMessage="*" ValidationGroup="Empty"
        ForeColor="Red"></asp:RequiredFieldValidator>
    &nbsp;
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Empty" />
</form>

In codebehind, add the following code.

protected void Page_Load(object sender, EventArgs e)
{
      txtDD.Attributes.Add("OnKeyUp", "OnKeyUpCheck(txtDD, txtMM, event)");
      txtMM.Attributes.Add("OnKeyUp", "OnKeyUpCheck(txtMM, txtYY, event)");
      txtYY.Attributes.Add("OnKeyUp", "OnKeyUpCheck(txtYY, btnSubmit, event)");
}

When you type invalid char(except 0-9), it show javascript alert. its length is meet and then it move focus to next control. Now, in web form, it uses server validation controls for empty text and they have ValidationGroup property.

No comments:

Post a Comment