在stackoverflow的帮助下,我用两个方法创建了一个.js文件,检查输入的日期是否有效。它工作正常,但只有日期以破折号输入 - 12/12/2019。我可以采用什么方法在isValidDate方法中使其适用于多个日期模式,例如 - 12.12.2020 12-12-2020等。我唯一的想法是先检查一下模式是什么,然后创建一个单独的案例用不同的字符分割日期字符串,但看起来很难看。
function isValidDate(dateString) {
var validDate = true;
// First check for the pattern
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
return false;
}
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[2], 10);
if(isNaN(day) || isNaN(month) || isNaN(year)){
return false;
}
// Check the ranges of month and year
if (year < 1000 || year > 3000 || month < 1 || month > 12) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
monthLength[1] = 29;
}
// Check the range of the day
if (!(day > 0 && day <= monthLength[month - 1])) {
return false;
}
return true;
};
/**
* Function which executes each time the input loses focus (onblur)
*/
function validateDate() {
// Get a reference to the container
var container = document.querySelector('.date');
// Clear stale error/success messages
container.className = container.className.replace('success', '');
container.className = container.className.replace('error', '');
// Get current value of input
var dateString = document.getElementById("Start-date").value;
// Test if the string is a valid date
var isValid = isValidDate(dateString);
// Update classess of container to show success/error
if (!isValid) {
container.className += ' error';
} else {
container.className += ' success';
}
}
我首先调用validateDate()函数
答案 0 :(得分:1)
请注意我没有测试过正则表达式,这只是一个如何攻击probelm的例子
//首先检查模式var = dateChar
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) { dateChar = '/'; } if (!/^\d{1,2}\-\d{1,2}\-\d{4}$/.test(dateString)) { dateChar = '-'; } if (!dateChar) { return false; } var parts = dateString.split(dateChar);
...