简体   繁体   中英

Validating form before submitting

I could submit a form and validate it using a simple anonymous function in javascript as,

 document.getElementById('myForm').onsubmit = function() {
     if(document.getElementById('email').value == "") {
         document.getElementById('errormessage').innerHTML = "Please provide at least an email address";
         return false;
     } else {
         return true; // Note this
     }
 };

In the example above using anonymous function, I could simply assign the return value when the document is submitted and prevent the page from being submitted while in the example below I use addEventListener to add event when the form is submitted and it is further evaluated by validate function. I have also placed the return value to be true or false but this approach does not seem to work and the page gets submitted. I think I am wrong in returning the value

function addEventHandler(node, evt, func) {
    if(node.addEventListener)
        node.addEventListener(evt, func);
    else
        node.attachEvent("on" + evt, func);
}
function initializeAll() {
    addEventHandler(document.getElementById('myform'), 'submit', validate);
}
function validate() {
    if(document.getElementById('email').value == ""){
        document.getElementById("errormessage").innerHTML = "Please provide at least an email ";
        return false;
    } else {
        return true;
    }
}
addEventHandler(window, 'load', initializeAll);

How should I return value this way so as to prevent the form from submitting or submitting the form?

You posted this question under jQuery, so I'll throw out a jQuery solution for ya:

$('#myform').on('submit', function () {
    if($('#email').val() == ""){
        $('#errormessage').html("Please provide at least an email ");
        return false;
    } else {
        return true;
    }
});

Note that I used the jQuery 1.7 .on() function which in this case replaces the .bind() function of earlier versions.

--Update--

Here is a jsfiddle of the above solution: http://jsfiddle.net/jasper/LmaYk/

I think your problem occurs because you are using the DOM Level 2 Event Registraton with addEventListener , so you can use event.preventDefault() for Firefox and event.returnValue=false to other browsers. Try with this demo:

http://jsfiddle.net/pYYSZ/42/

用这样的东西

<form ...... onsubmit="return your validationFunctionThatReturnTruOrFalse() " >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM