user2234760
user2234760

Reputation: 143

Getting "null or not an object" error when validating form

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.

Upvotes: 0

Views: 1486

Answers (2)

karaxuna
karaxuna

Reputation: 26940

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");
    });
});

Upvotes: 0

epascarello
epascarello

Reputation: 207527

Because you are calling it as the page renders so the element does not exist yet.

You need to have that code wrapped in some validation function that is called onsubmit.

Upvotes: 2

Related Questions