简体   繁体   English

使用JavaScript验证日期时间输入

[英]Validate datetime input using javascript

Im trying to validate a datetime user input using javascript for my school project, scheduling system. 我正在尝试为我的学校项目(计划系统)使用javascript验证日期时间用户输入。

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 . 您可以使用JavaScript Date对象保存输入的值并处理日期信息,并且可以在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.) 您可以在上面的链接中找到有用的方法(例如.getDay方法,该方法根据本地时区为您提供从零到六的数字。)

(Note: If you need to find out what timezone the script is running in (in minutes, relative to UTC time), use .getTimezoneOffset .) (注意:如果您需要找出脚本运行的时区(以分钟为单位,相对于UTC时间),请使用.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" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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