Shaoz
Shaoz

Reputation: 10653

How prevent submit if input are empty with javascript

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

Upvotes: 1

Views: 23654

Answers (4)

Naama Katiee
Naama Katiee

Reputation: 758

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

Upvotes: 6

Arka Dev
Arka Dev

Reputation: 56

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

Upvotes: 1

Angelos Kapsimanis
Angelos Kapsimanis

Reputation: 999

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>

Upvotes: 8

Carlo Moretti
Carlo Moretti

Reputation: 2250

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.

Upvotes: 1

Related Questions