/** * 驗證月份表單輸入是否合法 * pattern : 月份格式字符串 * id : 表單id */ function validateMonth(pattern, id) { var text = document.getElementById(id); var monthStr = text.value; var splitChar = ""; if(pattern.length > 6) splitChar = pattern.substring(4, pattern.length - 2); eval("var re = /\\d{4}" + splitChar + "\\d{2}$/;"); //var re = /\d{4}-\d{2}$/; if(monthStr.match(re) == null) { alert("請參考格式[" + pattern + "]輸入!\n" + "e.g \"2010" + splitChar + "11\" or \"2010" + splitChar + "03\""); text.value = ""; text.focus(); return false; } return true; }
需要動態拼出腳本字符串傳給eval()方法執行時,需要對字符'\'轉義