JavaScript Form Validation: Restrict Date Input to Past Month
<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<form>
<input type="date" name="date_of_join">
<button type="submit">Submit</button>
</form>
<script>
function watchForm() {
var form = document.querySelector('form');
form.watch([{\n 'fieldCode': 'date_of_join'
}], function(data) {
if (data['date_of_join'] && data['date_of_join'].length) {
var currentDate = new Date();
var oneMonthEarlier = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
var minDate = oneMonthEarlier.toISOString().split('T')[0];
var selectedDate = new Date(data['date_of_join']);
var selectedTimestamp = selectedDate.getTime();
console.log("selectedTimestamp=", selectedTimestamp)
var oneMonthEarlierTimestamp = oneMonthEarlier.getTime();
console.log("oneMonthEarlierTimestamp", oneMonthEarlierTimestamp)
if (selectedTimestamp < oneMonthEarlierTimestamp) {
form.actions({
type: 'msgbox',
message: "最早日期不得早于" + minDate,
data: { 'date_of_join': '' }
});
// alert("最早日期不得早于" + minDate);
}
}
});
}
watchForm();
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/qqIp 著作权归作者所有。请勿转载和采集!