1

I have a login form but I wanna check if the fields are empty then do not submit. I did `return false' on submit but the browser still loads a new page. How can I stop that?

JS:

var username = document.getElementById('usernameField');
    var password = document.getElementById('passwordField');
    var loginBtn = document.getElementById('loginBtn');
    var infoBox = document.getElementById('formInfo');

    var isEmpty = /^\s*$/;

    var addEventTo = function(id, type, fn, capture) {
        if (document.addEventListener) {
            id.addEventListener(type, fn, capture);
        } else {
            id.attachEvent('on'+type, fn);
        }
    };

    function checkIfAllEmpty() {
        var loginForm = document.getElementById('loginform'),
            allInputs = loginForm.getElementsByTagName('input'),
            max = allInputs.length,
            i;

            for (i = 0; i < max; i++) {
                if (allInputs[i].type !== 'submit') {

                    if (allInputs[i].match(isEmpty)) {
                        infoBox.innerHTML = 'All your fields are empty';
                        return false;
                    }
            }
        }
    }

    //addEventTo(loginBtn, 'click', checkIfAllEmpty, false);

    if (document.addEventListener) {
            loginBtn.addEventListener('submit', checkIfAllEmpty, false);
    } else {
            loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
    }

HTML:

<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
    <fieldset id="loginFieldset">
        <legend>Sign in</legend>
        <ol>
            <li>
                <label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
                <span>Please type in your username</span>
            </li>
            <li>
                <label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
                <span>Please type your password</span>
            </li>
            <li>
                <input type="submit" value="Sign in" id="loginBtn" />
            </li>
        </ol>
    </fieldset>
</form>

Many thanks

2
  • can you provide your HTML code of the form? or do you create the form dynamically? Commented May 9, 2012 at 12:35
  • Hi @Naama Katiee: I have added the HTML... Commented May 9, 2012 at 12:41

4 Answers 4

8

If it ok to go with html5 (works fine with newer versions of Safari, Chrome, Firefox, Opera > 11.00 but no IE as usual), you can add the required tag in your input field.

<p id="formInfo"></p>
  <form id="loginForm" method="post" action="#">
    <fieldset id="loginFieldset">
      <legend>Sign in</legend>
      <ol>
        <li>
         <label for="usernameField">Username</label>
         <input type="text" placeholder="Enter username" id="usernameField" required />
         <span>Please type in your username</span>
        </li>
        <li>
         <label for="passwordField">Password</label>
         <input type="password" placeholder="Enter password" id="passwordField" required />
         <span>Please type your password</span>
        </li>
        <li>
            <input type="submit" value="Sign in" id="loginBtn" />
        </li>
    </ol>
</fieldset>

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

1 Comment

What about entering just spaces? I just used this but it still submitting when entering blank spaces in the input fields.
6

Looks like the event listener of the onsubmit are not being added correctly, anyway the easiest way to do it is to add onsubmit="return someValidationFuncThatReturnTrueOrFalse()" in your form:

<form id="loginForm" method="post" action="#" onsubmit="return validate()">

can I ask why you're using this approach on your js code? it could be done much easily if your form is static ...

function validate() {
    if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
         alert("all fields are empty");
         return false;
    } else {
        return true;
    }
}

or something like that ...

1 Comment

But I cannot use any library for this, it has to be pure javascript
1

You can use the attribute disabled="disabled" for the form inputs :

http://www.w3schools.com/tags/att_input_disabled.asp

set the submit button as disabled, then add an onchange listener to each input field so that if every field is filled you remove the disable attribute and the user can subit the form.

Comments

1

I use Prototype (as a javascript framework) and this code should work:

js:

function checkEmpties() {
    var usr = $('username');
    var pass = $('pass');
    var frm = $('formId');


    if (usr.value && pass.value) {
        //frm.submit();
        alert('submit');
    } else {
        alert('failed');
    }
}

Event.observe(window, 'DomReady', function() {
    var btn = $('submitBtn');
    Event.observe('submitBtn', 'click', checkEmpties);
}

html:

<form id="formId">
    <input type="text" name="username" id="username" />
    <input type="password" name="pass" id="pass" />
    <input type="button" id="submitBtn" value="Send"  />
</form>

What it does: Once the document has loaded attaches an event observer to the button, so when it's clicked the function checkEmpties is called. This function will retrieve the value of the inputs and if they're not empty, submit the form.

Hope it helps

Comments

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.