0

I'm trying to make a simple register form that makes sure the username and password have been entered correctly before submitting. Here's my form:

<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">

    <label> Username
        <input type="text" name="username" />
    </label>

    <label> Password
        <input type="text" name="password" />
    </label>            

    <input type="submit" name="submit" value="Submit" class="button"/>

</form>

And here are my javascript functions:

function validate_username(username) {
        var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
        var str = username;

        if (!regex.test(str)) {
            alert("Your username must be between 5 and 15 characters in length");
            register.username.focus();
            return false;
        }
    }

function validate_password(password) {
        regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
        str = password;

        if (!regex.test(str)) {
            alert("Your password must be at least 6 characters in length and must contain at least 1 number");
            register.password.focus();
            return false;
        }
    }


//Validate register form
function validate_account_creation(form) {



return validate_username(form.username.value);
return validate_password(form.password.value);

return true;

}

The username function works fine and it validates that one every time. However, if the username is correct, the form submits. The second function never activates. If the first function doesn't return anything, shouldn't the second function then be called and validate the second field?

2
  • If you don't return anything in a function, it will return undefined. Commented Nov 22, 2014 at 14:09
  • Tip: configure a linting tool in your IDE. It should catch dead code in your validate_account_creation() function (multiple returns) Commented Nov 22, 2014 at 16:18

1 Answer 1

2

It's the return statements. A return aborts the rest of the function and returns the result, so your validation should look like:

Javascript

function validate_account_creation(form) {

    var username = validate_username(form.username.value);
    var password = validate_password(form.password.value);

    return username && password; // if both are true, submit form

}
Sign up to request clarification or add additional context in comments.

2 Comments

Why not return validate_username(form.username.value) && validate_password(form.password.value)?
It's the exact same thing, I just used variables to make it more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.