Accept only MMddyyyy format in TextBox from keyboard input using jQuery

Last Reply one month ago By pandeyism

Posted one month ago

I have a datepicker for textbox where user can select the date using datepicker where there is no issue but if user is trying to enter the date through keyboard i am able to enter all the alphabets,special charcters in text box but i need to allow only numbers in mm/dd/yyyy format using jquery how can i do this

<input type="text" id="TextDate" placeholder="MM/DD/YYYY" />

 

Posted one month ago
Hi @kavithav,
Please try the following

Date TextBox validation: Allow only digits and slash using JavaScript or jQuery

It might help you.

Cheers Andrea.

Posted one month ago

it should not allow while typing itself


Posted one month ago

Which date picker you are using?


Posted one month ago

Hey kavithav,

Please refer below sample.

HTML

<input type="text" id="TextDate" placeholder="MM/DD/YYYY" maxlength="10" />
<link type="text/css" rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
    $(function () {
        $("#TextDate").datepicker();
        $("#TextDate").on('keydown', function (e) {
            IsNumeric(this, e.keyCode);
        });
        var isShift = false;
        var seperator = "/";
        function IsNumeric(input, keyCode) {
            if (keyCode == 16) {
                isShift = true;
            }
            //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;
            }
        };
    });
</script>

Demo