Insert Slash in Date Field TextBox while typing using JavaScript

Introduction: Hello Guys, “Welcome back” Today, I am here with another one new great article. In this article I explained the implementation about how to automatically insert or added Slash character as User types in the TextBox of Date Field by using JavaScript. This article will explain that how to validate Date in dd/MM/yyyy format by automatically adding Slash character after adding second character and fourth character by using JavaScript.

Join our Channel  on Whtsapp and Telagram for All Updates                                          

JavaScript function for insert or add Slash in Date Field (TextBox)

On the window.onload event handler, firstly all the INPUT elements of HTML are fetched from HTML Table and then a FOR loop will be executed on the fetched elements. Inside the FOR loop, a condition will be performed to check, whether the HTML INPUT element is a TextBox and also whether it has a CssClass named date-format.If both the conditions are TRUE, then MaxLength attribute is added and its value is set to 10. The KeyDown event handler will be assigned which calls the IsNumeric JavaScript function. The KeyUp event handler will also be assigned which calls the ValidateDateFormat JavaScript function.

IsNumeric function

The IsNumeric function will allows only Numbers (digits) that will be entered in the TextBox by the user. It will take INPUT element and KeyCode (the code of the pressed key) as parameter. Then, a condition will be is executed  with checking the Key Codes and cancelling the all Key Codes which are not Numbers (digits) and it also automatically adds Slash ( / ) character.

ValidateDateFormat function

The function named ValidateDateFormat will be validate the value of date with the Regular Expression and if the validation not satisfied i.e. if the date Format is not dd/MM/yyyy, in the SPAN error message  will be displayed.

<script type="text/javascript">

    var isShift = false;

    var seperator = "/";

    window.onload = function () {

        //It will refer all the INPUT elements in the Table.

        var inputs = document.getElementsByTagName("input");

 

        //Loop will work on all INPUT elements in the Table.

        for (var i = 0; i < inputs.length; i++) {

            //It will Check if  the INPUT element is TextBox.

            if (inputs[i].type == "text") {

                //Check if the  Date Format Validation is required.

                if (inputs[i].className.indexOf("date-format") != 1) {

 

                    //Here you can Set Max Length.

                    inputs[i].setAttribute("maxlength", 10);

 

                    //Only allow Numeric Keys.

                    inputs[i].onkeydown = function (e) {

                        return IsNumeric(this, e.keyCode);

                    };

 

                    //Validate the  Date format entered by the user.

                    inputs[i].onkeyup = function (e) {

                        ValidateDateFormat(this, e.keyCode);

                    };

                }

            }

        }

    };

 

    function IsNumeric(input, keyCode) {

        if (keyCode == 16) {

            isShift = true;

        }

        //This will allow only Numeric Keys.

        if (((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode <= 37 || keyCode <= 39 || (keyCode >= 96 && keyCode <= 105)) && isShift == false) {

            if ((input.value.length == 2 || input.value.length == 5) && keyCode != 8) {

                input.value += seperator;

            }

 

            return true;

        }

        else {

            return false;

        }

    };

 

    function ValidateDateFormat(input, keyCode) {

        var dateString = input.value;

        if (keyCode == 16) {

            isShift = false;

        }

        var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;

 

        //Check whether valid dd/MM/yyyy Date Format.

        if (regex.test(dateString) || dateString.length == 0) {

            ShowHideError(input, "none");

        } else {

            ShowHideError(input, "block");

        }

    };

 

    function ShowHideError(textbox, display) {

        var div = textbox.parentNode;

        var spans = div.getElementsByTagName("span");

         for (var i = 0; i < spans.length; i++) {

                //Check whether SPAN has CSS class: error.

                if (spans[i].className.indexOf("error") != 1) {

                    //Show or hide HTML SPAN.

                    spans[i].style.display = display;

               }

          }

    };

</script>

 

 

Inserting (Add) Slash in Date Field (TextBox) using JavaScript

On the HTML page, we need to place controls  as TextBox and SPAN inside an DIV.The TextBox will be set with CSS class date-format. The SPAN element will be used for displaying error message and it must be set with a CSS class error. 

<div>

    Birth Date:

    <input type="text" class="date-format" />

    <span class="error" style="display: none">Invalid Date. Only dd/MM/yyyy format allowed.</span>

</div>

Here I am giving complete code for HTML page with JavaScript functions as well as controls. You need to copy and paste the code in your HTML page for enjoying the code.

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <style type="text/css">

        body { font-family: Arial; font-size: 10pt; }

        .error { color: Red; }

        span { padding-top: 5px }

    </style>

</head>

<body>

    <div>

        Birth Date:

        <input type="text" class="date-format" />

        <span class="error" style="display: none">Invalid Date. Only dd/MM/yyyy format allowed.</span>

    </div>

 

<script type="text/javascript">

    var isShift = false;

    var seperator = "/";

    window.onload = function () {

        //It will refer all the INPUT elements in the Table.

        var inputs = document.getElementsByTagName("input");

 

        //Loop will work on all INPUT elements in the Table.

        for (var i = 0; i < inputs.length; i++) {

            //It will Check if  the INPUT element is TextBox.

            if (inputs[i].type == "text") {

                //Check if the  Date Format Validation is required.

                if (inputs[i].className.indexOf("date-format") != 1) {

 

                    //Here you can Set Max Length.

                    inputs[i].setAttribute("maxlength", 10);

 

                    //Only allow Numeric Keys.

                    inputs[i].onkeydown = function (e) {

                        return IsNumeric(this, e.keyCode);

                    };

 

                    //Validate the  Date format entered by the user.

                    inputs[i].onkeyup = function (e) {

                        ValidateDateFormat(this, e.keyCode);

                    };

                }

            }

        }

    };

 

    function IsNumeric(input, keyCode) {

        if (keyCode == 16) {

            isShift = true;

        }

        //This will allow only Numeric Keys.

        if (((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode <= 37 || keyCode <= 39 || (keyCode >= 96 && keyCode <= 105)) && isShift == false) {

            if ((input.value.length == 2 || input.value.length == 5) && keyCode != 8) {

                input.value += seperator;

            }

 

            return true;

        }

        else {

            return false;

        }

    };

 

    function ValidateDateFormat(input, keyCode) {

        var dateString = input.value;

        if (keyCode == 16) {

            isShift = false;

        }

        var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;

 

        //Check whether valid dd/MM/yyyy Date Format.

        if (regex.test(dateString) || dateString.length == 0) {

            ShowHideError(input, "none");

        } else {

            ShowHideError(input, "block");

        }

    };

 

    function ShowHideError(textbox, display) {

        var div = textbox.parentNode;

        var spans = div.getElementsByTagName("span");

         for (var i = 0; i < spans.length; i++) {

                //Check whether SPAN has CSS class: error.

                if (spans[i].className.indexOf("error") != 1) {

                    //Show or hide HTML SPAN.

                    spans[i].style.display = display;

               }

          }

    };

</script>

 

</body>

</html>

 

Conclusion: In above code, I have been explained that how to automatically insert or added Slash character as User types in the TextBox of Date Field by using JavaScript. This code is very helpful for every developer. Bye Bye and take care of yourself Developers. We will come back shortly with the new article.

 

Regards

Programming Hub

 

 

0 comments:

Post a Comment