基本上我正在尝试编写一些用于表单验证的代码,我对此非常陌生但是我管理好吗?我的问题基本上就是这个,我已经为我的表单中的3个输入创建了3个验证方法但是我不太确定如何将所有3个方法添加到单击按钮中?
到目前为止,我的代码是:function validation() {
function validateName() {
console.log("reaching here");
var name = document.getElementById("full_name");
if (name.value.length == 0) {
document.getElementById("okName").className = "fail";
}else{
document.getElementById("okName").className = "success";
}
}//End of validate name
function validateEmail() {
var email = document.getElementById("email");
if (email.value.length == 0) {
document.getElementById("okEmail").className = "fail";
}else{
document.getElementById("okEmail").className = "success";
}
}//end of validate email
function validatePhone() {
var phone = document.getElementById("phone");
if (phone.value.length == 0) {
document.getElementById("okPhone").className = "fail";
}else{
document.getElementById("okPhone").className = "success";
}
}//End of validate phone
}//End of validation function
我也尝试从单个函数中删除所有验证方法,并将它们放在一个单独的函数中,但这也不起作用?如果有人能够解释我出错的地方那就太棒了!提前干杯!
答案 0 :(得分:1)
尝试将onclick()
事件附加到您的提交按钮 - http://jsfiddle.net/zWrUM/
<button onclick="validation();">validate</button>
<script>
function validation() {
var name = document.getElementById("full_name");
if (name.value.length == 0) {
document.getElementById("okName").className = "fail";
alert("error 1");
return false;
}else{
document.getElementById("okName").className = "success";
}
var email = document.getElementById("email");
if (email.value.length == 0) {
document.getElementById("okEmail").className = "fail";
alert("error 2");
return false;
}else{
document.getElementById("okEmail").className = "success";
}
var phone = document.getElementById("phone");
if (phone.value.length == 0) {
document.getElementById("okPhone").className = "fail";
alert("error 3");
return false;
}else{
document.getElementById("okPhone").className = "success";
}
alert("success")
}//End of validation function
</script>
答案 1 :(得分:0)
您可以查看addEventListener
和oldIE类似的方法。