Stop Submit With Empty Input Values

半城伤御伤魂 提交于 2019-12-21 04:52:24

问题


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.


回答1:


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>



回答2:


Possible approach:

  • setting action to #
  • adding handler to the submit button or the onsubmit of the form
  • change the action of the form, if text fields are not empty

Edit: To make this even work for non-javascript users insert the #-action when page is loaded.




回答3:


To keep it minimal I would just use:

<form id="login" method="post" action="" onSubmit="if (this.email.value == '' || this.pwd.value == '') {return false;}">

Granted - doesn't point out what's amiss to the user, but works a treat.



来源:https://stackoverflow.com/questions/1182755/stop-submit-with-empty-input-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!