我想使用JavaScript进行一些客户端验证,以检查字符串是否与正则表达式匹配:
我的js错了..?
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "30/12/2015";
var patt = new RegExp("DD/MM/YYYY");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
答案 0 :(得分:3)
这不是正则表达式。最简单(但相当天真)的解决方案是:
var isDateCorrect = new Date(str).toString() !== "Invalid Date";
new Date(str)
将尝试解析日期,如果失败,它将返回在调用toString
之后生成字符串Invalid Date
的对象,所以你得到了善意本机日期验证。
答案 1 :(得分:1)
正则表达式只检查输入字符串的格式:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "11/12/2015";
document.getElementById("demo").innerHTML = testDateFormat(str);
}
function testDateFormat(str) {
return (str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/)) ? true : false;
}
</script>
</body>
</html>
答案 2 :(得分:0)
DD/MM/YYYY
不是有效的RegEx。请改用\d\d\/\d\d\/\d\d\d\d
:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "30/12/2015";
var patt = new RegExp("\d\d\/\d\d\/\d\d\d\d");
var res = patt.test(str);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>