Kebman
Kebman

Reputation: 2089

How do I get two JavaScript references to the same HTML-form to work?

I'm having trouble validating an HTML form with JavaScript. On their own they each work, but together they don't.

This works:

// Make sure the e-mail address is valid
function validateEmail(mailform,email) { 
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = document.forms[mailform].elements[email].value;
    if(reg.test(address) == false) {
        alert('E-mail not valid');
        return false;
    } 
}

Attribute in the form:

onsubmit="javascript:return validateEmail('mailform', 'email');"

And this works:

// Make sure the message is long enough
function validateBody(mailform,mailbody) { 
    var msg = document.forms[mailform].elements[mailbody].value.length;
    if (msg < 3) {
        alert('Too hort');
        return false;
    }
}

Attribute in the form:

onsubmit="javascript:return validateBody('mailform', 'mailbody');"

But this doesn't work:

// Make sure the e-mail address is valid AND that the message is long enough
function validateForm(mailform,email,mailbody) { 
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = document.forms[mailform].elements[email].value;
    var msg = document.forms[mailform].elements[mailbody].value.length;
    if(reg.test(address) == false) {
        alert('Please enter a valid e-mail address');
        return false;
    } else if (msg < 3) {
        alert('Text too hort');
        return false;
    }
}

Attribute in the form:

onsubmit="javascript:return validateForm('mailform', 'email', 'mailbody');"

Why?

As I said, they work each on their own, but even as different functions, they don't work together.

Upvotes: 0

Views: 78

Answers (3)

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171559

You don't need to use javascript: in the onsubmit attribute, remove that part.

Also, you would benefit greatly from using a JavaScript library such as jQuery.

Upvotes: 1

Andrew Leach
Andrew Leach

Reputation: 12983

If you have two functions which work, why not use those?

function validateForm(mailform,email,mailbody) { 
var addressValid = validateEmail(mailform,email);
var bodyValid = validateBody(mailform,mailbody);
return addressValid && bodyValid
}

The return will only return true if both tests are true. The advantage of this method is (as well as being likely to work) that it's easily extended and easily maintained.

If you only want one alert if there are two errors, then you'll need to test addressValid and call bodyValid only if required.

Upvotes: 1

Engineer
Engineer

Reputation: 48813

Use if (msg < 3) instead of else if (msg < 3) .

Upvotes: 1

Related Questions