对名字,姓氏和电子邮件地址的JavaScript表单验证不显示任何内容

时间:2014-04-17 23:44:58

标签: javascript

我只是在复制我的代码:

HTML

<form id='test'>
Name *
    <input id="lname" type="text"><span id="wronglname" class="error">*This is a required field</span>
        Name *
    <input id="name" type="text"><span id="wrongname" class="error">*This is a required field</span>

Email*
    <input id="email" type="text"><span id="wrongemail" class="error">* Wrong Email Address</span>

    <div>
        <input type="submit" value="Submit">
    </div>
</form>

的Javascript

function ValidateForm() {

    var hasError = false;

    if (document.getElementById('lname').value == "") {
        document.getElementById('lwrongname').style.display = "inline";
        hasError = true;
    } else {
        document.getElementById('wrongname').style.display = "none";   
    }
        if (document.getElementById('name').value == "") {
        document.getElementById('wrongname').style.display = "inline";
        hasError = true;
    } else {
        document.getElementById('wrongname').style.display = "none";   
    }

    if (document.getElementById('email').value.search(/^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/) == -1) {
        document.getElementById('wrongemail').style.display = "inline";
        hasError = true;
    } else {
        document.getElementById('wrongemail').style.display = "none";   
    }

    return !hasError;
}


document.getElementById('test').onsubmit = ValidateForm;

CSS

.error {
    display:none;
    color:red;
}

我根本没有回复,每当我通过chrome检查javascript控制台时,它都显示我也没有错误,我不太确定我的编码有什么问题,有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:1)

这是你的错误:

if (document.getElementById('lname').value == "") {
        document.getElementById('lwrongname').style.display = "inline";
        hasError = true;
    }

注意document.getElementById('lwrongname'),应为document.getElementById('wronglname')