gpt4 book ai didi

javascript - JavaScript 中的日期验证器

转载 作者:行者123 更新时间:2023-12-03 01:59:39 26 4
gpt4 key购买 nike

我有几个月的 java 经验,但现在我正在尝试编写我的第一个 javascript 来验证日期输入。我不确定代码中有什么问题。

            <label for="Start-date" class="label">Available start date</label>
<input type="text" onsubmit="isValidDate()" class="w-input" maxlength="256" name="Start-date" data-name="Start date" placeholder="dd/mm/yyyy" id="Start-date" th:value="${possibleStartDate}" />
<script>
var validDate = true;
function isValidDate(){

var dateString = document.getElementById("Start-date");
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)){
validDate = false;
return;
}

// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);

// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12){
validDate = false;
return;
}

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])){
validDate = false;
return;
}else{
return;
}
};
if(!validDate){
alert("Invalid date!");
}
</script>

还有什么更好的替代警报?按下提交按钮时,文本字段下方会出现一条红色小消息,表明输入不正确。我知道最好为 javascript 提供单独的文件,但我不确定 html 中的何处放置标签来链接文件。

最佳答案

有很多事情需要稍微调整:

  1. var dateString = document.getElementById("Start-date") 应为 var dateString = document.getElementById("Start-date").value;

  2. var day = parseInt(parts[1], 10); 应为 var day = parseInt(parts[0], 10);var Month = parseInt(parts[0], 10); 应为 var Month = parseInt(parts[1], 10); 以支持 dd/mm/yyyy

  3. 输入不会触发 onsubmit,除非它们是表单的一部分,您可以尝试使用 onblur

  4. 我用 div 包装了输入,并用子项指示成功/错误,以更好地显示消息。 (使用根 div 上的类和支持样式隐藏显示消息)

  5. 我从 DOM 操作中分离出日期字符串的验证,以便您可以在多个位置重复使用验证

注释:

  1. 您最好将输入类型设置为日期(如果浏览器支持,它会打开日期选择器)
  2. 您还可以选择使用 momentjs 等库使常见的日期操作变得更容易一些。

/**
* Function which takes a string as an input and validates if it
* is a date in the dd/mm/yyyy format
* @param {string} dateString - The string representation of the date to validate
8 @returns {boolean} value indicating if the date is valid (true) or not (false)
*/
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';
}
}
div.date .error {
display: none;
background: red;
color: white;
}

div.date .success {
display: none;
background: darkgreen;
color: white;
}

div.date.success .success {
display: block;
}

div.date.error .error {
display: block;
}
<div class="date">
<label for="Start-date" class="label">Available start date</label>
<input type="text" onblur="validateDate()" class="w-input" maxlength="256" name="Start-date" data-name="Start date" placeholder="dd/mm/yyyy" id="Start-date" th:value="${possibleStartDate}" />
<div class="error">Please enter a valid date</div>
<div class="success">Date is valid</div>
</div>

关于javascript - JavaScript 中的日期验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50097114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com