用戶填寫信用卡資訊。如果用戶在今天之前輸入到期日期,我希望驗證能夠正常作業。但輸入如下;毫米/年。但是,用戶輸入年份的最后 2 位數字。例如,假設用戶輸入到期日期為 06/21。今天的日期是 06/22。在這種情況下,驗證應該起作用。我需要檢查用戶輸入的月份和年份。如果用戶輸入錯誤的日期,我想顯示錯誤訊息。我一直在尋找,但無法整合它。
我怎么解決這個問題?
const [errorList, setErrorList] = useState({
expDateValidationStateError: true,
});
const [expDateValidationState, setExpDateValidationState] = useState({
error: false,
helperText: '',
});
const expDateOnChange = (event) => {
if (expDateValidator(event.target.value)) {
setExpDateValidationState({ error: false, helperText: '' });
setErrorList({ ...errorList, expDateValidationStateError: false });
} else {
setExpDateValidationState({ error: true, helperText: t('payment-credit-card.error-messages.exp_date') });
setErrorList({ ...errorList, expDateValidationStateError: true });
}
};
uj5u.com熱心網友回復:
這是代碼:
const ccExpired = (date)=>{
const dateArr = date.split('/');
const exYear = dateArr[1] 2000;
const exMonth = dateArr[0] - 1; // JS months start with 0
const exDay = new Date(exYear,exMonth 1,0).getDate();
const dateObj = new Date(exYear,exMonth,exDay - 2); // Timezones fix.
const dateNow = new Date();
return dateNow > dateObj;
}
console.log("2/22 " ccExpired('2/22'));
console.log("3/33 " ccExpired('3/33'));
//This is for SO debug only, ignore.
const currentMonth = (new Date().getMonth() 1);
const currentYear = (new Date().getFullYear()).toString().replace(/^20/, '');
const thisMonth = `${currentMonth}/${currentYear}`;
const lastMonth = `${(currentMonth-1)}/${currentYear}`;
const nextMonth = `${(currentMonth 1)}/${currentYear}`;
console.log(thisMonth " " ccExpired(thisMonth));
console.log(lastMonth " " ccExpired(lastMonth));
console.log(nextMonth " " ccExpired(nextMonth));
uj5u.com熱心網友回復:
也許
const isCCExpired = str => {
const [mm,yy] = str.split("/");
const dateObj = new Date( yy 2000,mm-1,15); // months are 0 based and don't take the 1st due to timezones
console.log(dateObj);
return dateObj.getTime() < new Date().getTime();
};
console.log("3/22",isCCExpired('3/22'));
console.log("3/23",isCCExpired('3/23'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493088.html
標籤:javascript 反应 反应式
