验证表单时出现“null或not an object”错误

时间:2013-04-25 13:46:11

标签: javascript forms validation null

我正在使用它:

<script type="text/javascript">
    var emailRule = /^[_\w\-]+(\.[\w\-]+)*(\.[\D]{2,3})$/;

    if (emailRule.test(document.forms[0].email.value))
        window.alert("That was a valid email address");
    else
        window.alert("That was not a valid email address");
</script>

验证这一点:

<form action="">
    <p>Email: <input type="text" name="email"/>
    <input type="submit" value="Sign up"/></p>
    <br>
</form>

该表单是页面上唯一的表单,该输入框是页面上唯一的表单元素。我收到这个错误:

document.forms.0.email is null or not an object

我也尝试将其更改为document.forms[0].elements[0].value,但我得到了相同类型的错误。

2 个答案:

答案 0 :(得分:2)

因为您在页面渲染时调用它所以元素尚不存在。

您需要将该代码包含在一些名为onsubmit的验证函数中。

答案 1 :(得分:0)

var emailRule = /^[_\w\-]+(\.[\w\-]+)*(\.[\D]{2,3})$/;

window.addEventListener('load', function(){
    var form = document.forms[0];
    form.addEventListener('submit', function(e){
        if (!emailRule.test(form.email.value)){
            window.alert("That was not a valid email address");
            e.preventDefault();
        } else
            window.alert("That was a valid email address");
    });
});