我拿到這個劇本腳本來驗證生日
$("#SocialSecurityNumber").attr("placeholder","YYYY-MM-DD-XXXX").blur(function() {
var str = $('#SocialSecurityNumber').val();
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1], res[2], res[3]);
if (todays_date - birth_date > 565633905872) {
$("#btn-activation").removeAttr('disabled');
$("#SocialSecurityNumber").removeClass("input-validation-error");
} else {
$("#SocialSecurityNumber").attr("placeholder","Please enter date of birth as YYYY-MM-DD-XXXX").addClass("input-validation-error");
$("#btn-activation").attr("disabled", "disabled");
}
});
});
這將驗證年齡,從輸入#SocialSecurityNumber 然而,輸入文字或當其他jibberish它沒有在所有的驗證,我得到JS錯誤
Uncaught TypeError: Cannot read property '1' of null
可以幫助我如何添加,所以這個腳本也驗證不正確的字符嗎? (當正則表達式不匹配時)
如果RegEx不匹配,那麼'res'將爲空...因此調用索引時總會失敗。在執行'res [1]'之前,你需要測試'res!= null'(或類似的) – freefaller