skip to Main Content

`I am working on a date time input inside a web app. The format for date and time is MM/DD/YYYY HH:MM:SS. I have to validate the month, date and year. For example, it should prevent user from entering 13 instead of 12 in the month placeholder.

Below is html code.

<label>Date time:
        <input placeholder="__/__/____ __:__:__" data-slots="_">
</label><br>

and the js

<script>
        document.addEventListener('DOMContentLoaded', () => {
            for (const el of document.querySelectorAll("[placeholder][data-slots]")) {
                const pattern = el.getAttribute("placeholder"),
                    slots = new Set(el.dataset.slots || "_"),
                    prev = (j => Array.from(pattern, (c, i) => slots.has(c) ? j = i + 1 : j))(0),
                    first = [...pattern].findIndex(c => slots.has(c)),
                    accept = new RegExp(el.dataset.accept || "\d", "g"),
                    clean = (input) => {
                        input = input.match(accept) || [];
                        return Array.from(pattern, c =>
                            input[0] === c || slots.has(c) ? input.shift() || c : c
                        );
                    },
                    format = () => {
                        const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {
                            i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));
                            return i < 0 ? prev[prev.length - 1] : back ? prev[i - 1] || first : i;
                        });
                        el.value = clean(el.value).join``;
                        el.setSelectionRange(i, j);
                        back = false;
                    };
                let back = false;
                el.addEventListener("keydown", (e) => back = e.key === "Backspace");
                el.addEventListener("input", format);
                el.addEventListener("focus", format);
                el.addEventListener("blur", () => el.value === pattern && (el.value = ""));
            }

        });
    </script>

Even if its in jquery, its fine but please no External libraries or plugins.

I have tried to prevent it using prevent.default() for keypress event but have reached nowhere.
I just want the user to be prevented from entering wrong date instead of validating after entered.`

2

Answers


  1. Not sure you wanted this, but you can consider using the datepicker (jQuery + datepicker.js).
    add tags:

    <script type="text/javascript" src="../Scripts/jQuery/jquery.min.js"></script>
    
    <script type="text/javascript" src="../Scripts/jQuery/bootstrap-datepicker.js"></script>
    <link rel="stylesheet" href="../CSS/bootstrap-datepicker.css" type="text/css">
    

    Html:

    <input id="myDate" name="myDate" type="text" class="form-control date-input" placeholder="DD MM YYYY HH:MM:SS" readonly />
    

    jQuery:

        $(function () {
            $('#myDate').datepicker({
                //format of your date displayed
                format: "M/d/yyyy h: mm tt"
            }).on('changeDate', function (e) {
                //some code here
            });
    

    Sorry if it’s not what you were looking for

    Login or Signup to reply.
  2. You can do this

    <input type="datetime-local" required id="date" name="date">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search