Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Submit With Empty Input Values

Im Looking for a simple solution to stop a login form from submitting with empty input fields. The code for the form is below. I would like to use a simple Javascript soluiton if possible.

<form id="login" method="post" action=""> 
    <input type="text" name="email" id="email" /> 
    <input type="password" name="pwd" id="pwd" /> 
    <button type="submit" id="submit">Login</button>
</form>     

If possible I would also like to change the border of the empty field(s).

Thanks in advance.

like image 414
Brad Birdsall Avatar asked Jul 25 '09 18:07

Brad Birdsall


People also ask

How do you stop something from submitting?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do you stop an empty input react?

To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.


1 Answers

Sample code with dummy checks:

<script type="text/javascript">
function checkForm(form) {
    var mailCheck = checkMail(form.elements['email']),
        pwdCheck = checkPwd(form.elements['pwd']);
    return mailCheck && pwdCheck;
}

function checkMail(input) {
    var check = input.value.indexOf('@') >= 0;
    input.style.borderColor = check ? 'black' : 'red';
    return check;
}

function checkPwd(input) {
    var check = input.value.length >= 5;
    input.style.borderColor = check ? 'black' : 'red';
    return check;
}
</script>

<style type="text/css">
#login input {
    border: 2px solid black;
}
</style>

<form id="login" method="post" action="" onsubmit="return checkForm(this)"> 
    <input type="text" name="email" id="email" onkeyup="checkMail(this)"/> 
    <input type="password" name="pwd" id="pwd" onkeyup="checkPwd(this)"/> 
    <button type="submit" id="submit">Login</button>
</form>
like image 135
Christoph Avatar answered Sep 23 '22 22:09

Christoph