时间:2021-07-01 10:21:17 帮助过:109人阅读
/**
* 验证月份表单输入是否合法
* 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;
}
代码如下:
/**
* 验证月份表单输入是否合法
* 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()方法执行时,需要对字符'\'转义
方法二:
代码如下:
<script>
var n=new Array( ".htm ", ".html ", ".shtml ");
//var pattern1 = new RegExp( "\\w+\\ "+n[0]+ "$ ", "gi ");
var s1= "b.shtml ";
var result = false;
for(var i=0;i <n.length;i++)
{
pattern1 = new RegExp( "\\w+\\ "+n[i]+ "$ ", "gi ");
result|=pattern1.test(s1);
}
alert(Boolean(result));
</script>