Home > Web Front-end > JS Tutorial > jQuery Check if Date is Valid

jQuery Check if Date is Valid

Lisa Kudrow
Release: 2025-03-01 08:51:14
Original
1009 people have browsed it

jQuery Check if Date is Valid

Simple JavaScript function is used to check if the date is valid.

function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
}

//测试
var currentDate = new Date('31/09/2011');
console.log(isValidDate(currentDate.toString()));
console.log(isValidDate('30/09/2011'));
Copy after login

JavaScript function is used to get the number of days in a month.

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

//测试
daysInMonth('09','2011');
//输出: 30
Copy after login

See also:- jQuery Get future date

  • JavaScript date displays year error
  • jQuery date and time function - complete list

JavaScript function is used to check if the date is valid and if it is invalid, it will be set to the last day of the month.

/* 检查日期是否有效,如果无效则恢复到当月最后一天 */
validateDateLastDayMonth: function() {
    /* 辅助函数 */
    function isValidDate(s) {
      var bits = s.split('/');
      var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
      return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
    } 

    function daysInMonth(month, year) {
        return new Date(year, month, 0).getDate();
    }

    /* 初始化 */
    var currentDate = new Date(),
    currentMonth = currentDate.getMonth() + 1,
    lastDayOfMonth = new Date(currentDate.getFullYear(), (currentDate.getMonth() - 1), 0).getDate(),
    departureDate = FCL.DATETIME.futureDateDays(14),
    depDate = departureDate.split('/'),
    departureDateMonth = depDate[1];
    if (departureDateMonth != currentMonth) {
        departureDate = FCL.DATETIME.leadingZero(lastDayOfMonth) +'/'+ FCL.DATETIME.leadingZero(currentMonth) +'/'+ depDate[2];
    }

    /* 验证日期 */
    if (!isValidDate(departureDate.toString())) {
        var bits = departureDate.split('/');
        departureDate = FCL.DATETIME.leadingZero(daysInMonth(bits[1],bits[2])) +'/'+ FCL.DATETIME.leadingZero(currentMonth) +'/'+ depDate[2];
    }

    $('input[name="depDate"]').val(departureDate);
}
Copy after login

jQuery date verification FAQs (FAQs)

How to use jQuery to verify dates in a specific format?

jQuery provides a method called $.datepicker.parseDate that can be used to verify dates in a specific format. This method takes two parameters: date format and date string. If the date string matches the format, the method returns a Date object. If it does not match, an error will be raised. Examples are as follows:

try {  
 $.datepicker.parseDate('dd/mm/yy', '31/12/2020');  
 console.log('日期有效');  
} catch (error) {  
 console.log('日期无效');  
}
Copy after login

What is a jQuery verification plugin and how do you use it for date verification?

jQuery Verification Plugin provides a powerful client form verification framework. It includes built-in verification methods for common needs including date verification. To use it, you need to include the plugin in your project and call the validate method on the form. You can specify rules for each form field, including date fields. For example:

$('form').validate({  
 rules: {  
 dateField: {  
 date: true  
 }  
 }  
});
Copy after login

How to use jQuery to verify date range?

To verify the date range, you can use the $.datepicker.parseDate method to convert the date string to a Date object and then compare. Examples are as follows:

var startDate = $.datepicker.parseDate('dd/mm/yy', '01/01/2020');  
var endDate = $.datepicker.parseDate('dd/mm/yy', '31/12/2020');  

if (startDate > endDate) {  
 console.log('开始日期晚于结束日期');  
} else {  
 console.log('日期范围有效');  
}
Copy after login

Can I use jQuery to verify the date without using the plugin?

Yes, you can use the built-in JavaScript Date object to verify dates without using plug-ins. However, this method is not as flexible and more complex as using plug-ins or $.datepicker.parseDate. Examples are as follows:

var dateString = '31/12/2020';  
var dateParts = dateString.split('/');  
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);  

if (dateObject.getDate() == dateParts[0] && dateObject.getMonth() == dateParts[1] - 1 && dateObject.getFullYear() == dateParts[2]) {  
 console.log('日期有效');  
} else {  
 console.log('日期无效');  
}
Copy after login

The rest of the FAQ content is similar to the above, but the description of the problem and the code example have been slightly adjusted. In order to avoid duplication, I will not repeat it here. The core idea is to verify the validity of dates based on JavaScript's Date object and jQuery's $.datepicker.parseDate method. Different problems only differ in verification conditions, such as date format, date range, leap year, etc.

The above is the detailed content of jQuery Check if Date is Valid. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template