简体   繁体   中英

Validate datetime input using javascript

Im trying to validate a datetime user input using javascript for my school project, scheduling system.

I have already done this server side, is this possible client side?

<!--My code looks like this-->
<body>
    <input type="datetime-local" id="dateTimeInput">
    <input type="button" onclick="checkDateTimeInput()" value="Submit">
</body>
<script type="text/javascript">
    function checkDateTimeInput(){
    var dateTime = document.getElementById('dateTimeInput');
    if(dateTime /* not 2 or more days ahead */)
        alert("Must be 2 days ahead");
    }else if(dateTime /* is sunday */){
        alert("It is Sunday");
    }else if(dateTime /* not between 8AM-5PM */){
        alert("Time must be between 8AM-5PM");
    }else{
        alert("Success")
    }
</script>

Maybe something like this:

<body>
    <input type="datetime-local" id="dateTimeInput">
    <input type="button" onclick="checkDateTimeInput()" value="Submit">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with- 
     locales.min.js"></script>
    <script>
        let date = document.getElementById('dateTimeInput')
        let dateToValidate = null

        date.addEventListener('input', (e) => {
            dateToValidate = e.target.value
        })

        function checkDateTimeInput() {
            const today = moment().add(2, 'day')
            if (dateToValidate) {
                dateToValidate = moment(dateToValidate)
                if (dateToValidate.format('dd') === 'Su') {
                    alert('Sunday is not allowed')
                }
                else if (today >= dateToValidate) {
                    alert('Date has to be more than two days in the future')
                }
                else {
                    alert(dateToValidate.format('YYYY-MM-DD'))
                }

            } else {
                alert('Enter a valid date')
            }
        }
    </script>
</body>

You can use a JavaScript Date object to hold the value of your input and manipulate date information, and you can learn much more about these on MDN .

Here's a detailed explanation of how to use them to check for just the date difference (intentionally verbose for teaching purposes):

 const btn = document.getElementById("btn"); btn.addEventListener("click", checkDatetimeInput); function checkDatetimeInput(){ // Stores values in local variables const datetimeInput = document.getElementById("datetimeInput"), // HTML element datetimeInputValue = datetimeInput.value, // Value property in the HTML element dateObject = new Date(datetimeInputValue), // JS `Date` object dateObjectTimestamp = dateObject.getTime(), // Timestamp (milliseconds) dateString = dateObject.toUTCString(); // Human-readable string (See also `toLocaleString`) // Prints contents of variables console.log(`datetimeInputValue: ${ datetimeInputValue }`); console.log(`dateObjectTimestamp: ${ dateObjectTimestamp }`); console.log(`dateString: ${ dateString }`); console.log(``); // Calls function to check date difference, stores result in `tooSoon` const tooSoon = isLessThanTwoDaysFromNow(dateObject), // Calls remaining validation functions, stores results in variables sunday = isSunday(dateObject), daytimeHours = isBetweenEightAndFive(dateObject); // Prints final output let output = ""; if (tooSoon) { output = "That's too soon"; } else if(sunday) { output = "That's a Sunday"; } else if(!daytimeHours){ output = "That's not between 8 and 5"; } else { output = "Success! -- but did you check Sunday & time of day?"; } console.log(output); } function isLessThanTwoDaysFromNow(dateObjectFromInput){ // Stores values in local variables const nowObject = new Date(), // Default Date constructor uses the current time nowObjectTimestamp = nowObject.getTime(), // `getTime` gives a timestamp in milliseconds datetimeObjectTimestamp = dateObjectFromInput.getTime(), differenceInMilliseconds = datetimeObjectTimestamp - nowObjectTimestamp, differenceInDays = differenceInMilliseconds / (1000 * 60 * 60 * 24), diffferenceInDaysRoundedDown = Math.floor(differenceInDays), differenceInDaysIsLessThanTwo = differenceInDays < 2; // Prints contents of variables console.log(`differenceInMilliseconds: ${ differenceInMilliseconds }`); console.log(`differenceInDays: ${ differenceInDays }`); console.log(`diffferenceInDaysRoundedDown: ${ diffferenceInDaysRoundedDown }`) console.log(`differenceInDaysIsLessThanTwo: ${ differenceInDaysIsLessThanTwo }`); // Returns `true` or `false` to code that called this function return differenceInDaysIsLessThanTwo; } function isBetweenEightAndFive(dateObjectFromInput){ let result = true; // Test time of day here // (Be aware of the difference between UTC time and local time) return result; } function isSunday(dateObjectFromInput){ let result = false; // Test day of week here // (Be aware of the difference between UTC time and local time. // For example, Sunday 11:00PM EST might be Monday 4:00AM UTC.) return result; } 
 <input type="datetime-local" id="datetimeInput" /> <input type="button" id="btn" value="Submit" /> 

I leave it to you to check the day of the week and the time of day.

You can find useful methods for this at the link above (such as the .getDay method, which gives you a number from zero to six according to the local timezone.)

(Note: If you need to find out what timezone the script is running in (in minutes, relative to UTC time), use .getTimezoneOffset .)

 const btn = document.getElementById("btn"); btn.addEventListener("click", checkDatetimeInput); function checkDatetimeInput(){ var errors = ""; // Stores values in local variables const datetimeInput = document.getElementById("datetimeInput"), // HTML element datetimeInputValue = datetimeInput.value, // Value property in the HTML element dateObject = new Date(datetimeInputValue), // JS `Date` object dateObjectTimestamp = dateObject.getTime(), // Timestamp (milliseconds) dateString = dateObject.toUTCString(); // Human-readable string (See also `toLocaleString`) // Prints contents of variables console.log(`datetimeInputValue: ${ datetimeInputValue }`); console.log(`dateObjectTimestamp: ${ dateObjectTimestamp }`); console.log(`dateString: ${ dateString }`); // Calls function to check date difference, stores result in `notSoon` const notSoon = isAtLeastTwoDaysFromNow(dateObject) if(!notSoon) errors += "Must be 2 or more days ahead"; // Now you will need to do the other two checks (day of week and time of day)... var day = dateObject.getDay(); if(day == 0) errors += "\\nSunday not allowed"; var hourTime = dateObject.getHours(); if(hourTime < 8 || hourTime > 17) errors += "\\nInvalid time"; alert(errors); } function isAtLeastTwoDaysFromNow(myDatetime){ // Stores values in local variables const nowObject = new Date(), // Default Date constructor uses the current time nowObjectTimestamp = nowObject.getTime(), // `getTime` gives a timestamp in milliseconds datetimeObjectTimestamp = myDatetime.getTime(), differenceInMilliseconds = datetimeObjectTimestamp - nowObjectTimestamp, differenceInDays = differenceInMilliseconds / (1000 * 60 * 60 * 24), diffferenceInDaysRoundedDown = Math.floor(differenceInDays); differenceInDaysIsTwoOrMore = differenceInDays >= 2; // Prints contents of variables console.log(`differenceInMilliseconds: ${ differenceInMilliseconds }`); console.log(`differenceInDays: ${ differenceInDays }`); console.log(`diffferenceInDaysRoundedDown: ${ diffferenceInDaysRoundedDown }`) console.log(`differenceInDaysIsTwoOrMore: ${ differenceInDaysIsTwoOrMore }`); // Returns `true` or `false` to code that called this function return differenceInDaysIsTwoOrMore; 
 <input type="datetime-local" id="datetimeInput" /> <input type="button" id="btn" value="Submit" /> 

 const btn = document.getElementById("btn"); btn.addEventListener("click", checkDatetimeInput); function checkDatetimeInput(){ // Stores values in local variables const datetimeInput = document.getElementById("datetimeInput"), // HTML element datetimeInputValue = datetimeInput.value, // Value property in the HTML element dateObject = new Date(datetimeInputValue), // JS `Date` object dateObjectTimestamp = dateObject.getTime(), // Timestamp (milliseconds) dateString = dateObject.toUTCString(); // Human-readable string (See also `toLocaleString`) // Prints contents of variables console.log(`datetimeInputValue: ${ datetimeInputValue }`); console.log(`dateObjectTimestamp: ${ dateObjectTimestamp }`); console.log(`dateString: ${ dateString }`); // Calls function to check date difference, stores result in `tooSoon` const tooSoon = isLessThanTwoDaysFromNow(dateObject), // Calls remaining validation function, stores results in variables sunday = isSunday(dateObject), daytimeHours = isBetweenEightAndFive(dateObject); // Prints final output let output = ""; if (tooSoon) { output = "That's too soon"; } else if(sunday) { output = "That's a Sunday"; } else if(!daytimeHours){ output = "That's not between 8 and 5"; } else { output = "Success! -- but did you check Sunday & time of day?"; } console.log(output); } function isLessThanTwoDaysFromNow(dateObjectFromInput){ // Stores values in local variables const nowObject = new Date(), // Default Date constructor uses the current time nowObjectTimestamp = nowObject.getTime(), // `getTime` gives a timestamp in milliseconds datetimeObjectTimestamp = dateObjectFromInput.getTime(), differenceInMilliseconds = datetimeObjectTimestamp - nowObjectTimestamp, differenceInDays = differenceInMilliseconds / (1000 * 60 * 60 * 24), diffferenceInDaysRoundedDown = Math.floor(differenceInDays), differenceInDaysIsLessThanTwo = differenceInDays < 2; // Prints contents of variables console.log(`differenceInMilliseconds: ${ differenceInMilliseconds }`); console.log(`differenceInDays: ${ differenceInDays }`); console.log(`diffferenceInDaysRoundedDown: ${ diffferenceInDaysRoundedDown }`) console.log(`differenceInDaysIsLessThanTwo: ${ differenceInDaysIsLessThanTwo }`); // Returns `true` or `false` to code that called this function return differenceInDaysIsLessThanTwo; } function isBetweenEightAndFive(dateObjectFromInput){ let result = true; // Test time of day here // (Be aware of the difference between UTC time and local time) return result; // } function isSunday(dateObjectFromInput){ let result = false; // Test day of week here // (Be aware of the difference between UTC time and local time. // For example, Sunday 11:00PM EST might be Monday 4:00AM UTC.) return result; } 
 <input type="datetime-local" id="datetimeInput" /> <input type="button" id="btn" value="Submit" /> 

 const btn = document.getElementById("btn"); btn.addEventListener("click", checkDatetimeInput); function checkDatetimeInput(){ // Stores values in local variables const datetimeInput = document.getElementById("datetimeInput"), // HTML element datetimeInputValue = datetimeInput.value, // Value property in the HTML element dateObject = new Date(datetimeInputValue), // JS `Date` object dateObjectTimestamp = dateObject.getTime(), // Timestamp (milliseconds) dateString = dateObject.toUTCString(); // Human-readable string (See also `toLocaleString`) // Prints contents of variables console.log(`datetimeInputValue: ${ datetimeInputValue }`); console.log(`dateObjectTimestamp: ${ dateObjectTimestamp }`); console.log(`dateString: ${ dateString }`); // Calls function to check date difference, stores result in `tooSoon` const tooSoon = isLessThanTwoDaysFromNow(dateObject), // Calls remaining validation function, stores results in variables sunday = isSunday(dateObject), daytimeHours = isBetweenEightAndFive(dateObject); // Prints final output let output = ""; if (tooSoon) { output = "That's too soon"; } else if(sunday) { output = "That's a Sunday"; } else if(!daytimeHours){ output = "That's not between 8 and 5"; } else { output = "Success! -- but did you check Sunday & time of day?"; } console.log(output); } function isLessThanTwoDaysFromNow(dateObjectFromInput){ // Stores values in local variables const nowObject = new Date(), // Default Date constructor uses the current time nowObjectTimestamp = nowObject.getTime(), // `getTime` gives a timestamp in milliseconds datetimeObjectTimestamp = dateObjectFromInput.getTime(), differenceInMilliseconds = datetimeObjectTimestamp - nowObjectTimestamp, differenceInDays = differenceInMilliseconds / (1000 * 60 * 60 * 24), diffferenceInDaysRoundedDown = Math.floor(differenceInDays), differenceInDaysIsLessThanTwo = differenceInDays < 2; // Prints contents of variables console.log(`differenceInMilliseconds: ${ differenceInMilliseconds }`); console.log(`differenceInDays: ${ differenceInDays }`); console.log(`diffferenceInDaysRoundedDown: ${ diffferenceInDaysRoundedDown }`) console.log(`differenceInDaysIsLessThanTwo: ${ differenceInDaysIsLessThanTwo }`); // Returns `true` or `false` to code that called this function return differenceInDaysIsLessThanTwo; } function isBetweenEightAndFive(dateObjectFromInput){ let result = true; // Test time of day here // (Be aware of the difference between UTC time and local time) return result; // } function isSunday(dateObjectFromInput){ let result = false; // Test day of week here // (Be aware of the difference between UTC time and local time. // For example, Sunday 11:00PM EST might be Monday 4:00AM UTC.) return result; } 
 <input type="datetime-local" id="datetimeInput" /> <input type="button" id="btn" value="Submit" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM