我的代码有问题。如果我不匹配正则表达式,它应该显示红色输入框,否则它应该显示为绿色输入框。
function IsValid(pole, regex) {
if (regex.test(pole.value)) {
pole.className = "ok";
return true;
} else {
pole.className = "chyba";
return false;
}
}
function OnSubmit(form) {
if (IsValid(form.filter_date, dateReg)) {
return true;
} else {
return false;
}
}
window.onload = init;
function init() {
var filter_date = document.getElementById("filter_date");
dateReg = /^\d{2}-\d{2}-\d{4}$/;
filter_date.onblur = function() {
IsValid(this, dateReg);
}
document.forms("filter_form").onsubmit = function() {
return OnSubmit(this);
}
}
.ok {
background-color: red;
}
.chyba {
background-color: green;
}
<form id="filter_form" name="filter_form" action="" method="post">
<table class="filter_training" cellspacing="0" width="100%">
....
<input type="text" id="filter_date" name="filter_date" placeholder="01-01-1970" />....
</table>
</form>
最佳答案
1). 主要问题是 onsubmit
处理程序应该以这种方式绑定(bind):
document.forms.filter_form.onsubmit = function(){
return OnSubmit(this);
}
因为 document.forms("filter_form")
会抛出错误,因为 document.forms
是一个集合,而不是一个函数。
2). 另一个小问题是你混淆了颜色,应该是:
.ok { background-color: green; }
.chyba { background-color: red; }
演示:http://jsfiddle.net/fjm9yhdx/
关于JavaScript 正则表达式未验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994097/