0

I'm using this:

<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>

to validate this:

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

That form is the only form on the page and that input box is the only form element on the page. I get this error:

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

I've also tried changing it to document.forms[0].elements[0].value but I get the same type of error.

4

2 回答 2

2

因为您在页面呈现时调用它,所以该元素尚不存在。

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

于 2013-04-25T13:47:10.310 回答
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");
    });
});
于 2013-04-25T13:51:30.747 回答