最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I use javascript to prevent form submission because of empty fields? - Stack Overflow

programmeradmin0浏览0评论

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.

Share Improve this question asked Aug 7, 2013 at 0:53 ZippyliciousZippylicious 1852 gold badges5 silver badges12 bronze badges 1
  • 2 You shouldn't trust javascript. You can use it so that your server has less work, but your php script must know how to validate data. If not, your script is vulnerable – Oriol Commented Aug 7, 2013 at 0:57
Add a ment  | 

4 Answers 4

Reset to default 3

HTML Code :-

<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>

Javascript Code :-

  function runMyFunction()
    {
        if (document.getElementsByName("name")[0].value == "")
        {
            alert("Please enter value");
        }
        else
        {
            var form= document.getElementsByName("form")[0];
            form.submit();        
        }
    }

Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.

If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName

function checkForm(form1)
{
    if (form1.elements['FieldName'].value == "")
    {
        alert("You didn't fill out FieldName - please do so before submitting");
        return false;
    }
    else
    {
        form1.submit();
        return false;
    }
}

This is untested code but it demonstrates my method.

It will check any text field in 'form' for empty values, and cancel the submit action if there are any.

Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.

window.onload = function (event) {
    var form = document.getElementsByName('form')[0];
    form.addEventListener('submit', function (event) {
        var inputs = form.getElementsByTagName('input'), input, i;
        for (i = 0; i < inputs.length; i += 1) {
            input = inputs[i];
            if (input.type === 'text' && input.value.trim() === '') {
                event.preventDefault();
                alert('You have empty fields remaining.');
                return false;
            }
        }
    }, false);
};

Attach an event handler to the submit event, check if a value is set (DEMO).

var form = document.getElementById('test');

if (!form.addEventListener) {
    form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
    form.addEventListener("submit", checkForm, false);
}

function checkForm(e) { 
    if(form.elements['name'].value == "") {
        e.preventDefault();
        alert("Invalid name!");   
    }
}
发布评论

评论列表(0)

  1. 暂无评论