简体   繁体   中英

Validate form before move to next page

I have coded my own validation form. Is there anyway i can prevent page from submit to php (action="process.php" Method="POST") if form is not validated. I have been thinking all day. I have tried with ajax and json. When all fields validated the page never moves an inch or redirect. Please i prefer my solution in pure javascript. I don't like the frameworks, jquery and stuff. https://codeshare.io/zy91Q7


      function validateForm() {
  
  firname();
  lasname();
  addr();
  citnma(),
  zipx();
  checkEmail();
  phnc();

}

This solution is just plain js and html. It will need adjustments on validation requirements. It is only an idea to handle multiple form elements for validation before submitting.

Here is the "raw" example which can be run from any browser.

I will follow up with an example that can be run from here Stack Overflow.

Note that in this SOLUTION the error won't refresh to blank of any input change after the error occurred. You can add this logic in if you like.

I included code comments to explain as it goes along in the code.

RAW CODE TO PASTE TO YOUR EDITOR TEST:

<html>
<body>
<!-- give all your input, select, and textarea fields IDs so they can be referenced via javascript -->
<!-- You can still give the "name" attributes if they are to be submitted. -->

<!-- give the form an ID. Remove any explicity "submit" button -->

<!-- Cant real form line here to test -->
<!--form id="theForm" action="" method="" -->

<form id="theForm"> <!-- for testing here on SO -->
    A <input type id="a" name="a"><br/>
    B <input type id="b" name="b"><br/>
    <div id="form_error_message"></div>
    
</form>

<!-- Use type button on button ( and don't name oncick script submit(), important ) -->

<button type="button" onclick="validateFormOrSubmit()">Submit</button>

<script>
function errorsFormFrontEnd() {
    // returns an array of unacceptable input
    // Change these conditionals based on needs of valid form
    
    let errors = [];
    
    // TODO: trim .value to rid white space, not done in this example
    
    if ( document.getElementById("a").value == "") errors.push("a");
    if ( document.getElementById("b").value == "") errors.push("b");
    
    // it would have been easier (typing wise) to loop through form elements above,
    // but I didn't because this an example of the concept.
    
    return errors;
    
}
</script>

<!-- Start new script tags per function so broke code in one doesn't break the other, useful for debugging -->

<script>

function validateFormOrSubmit() {
    
    
    let errors = errorsFormFrontEnd();
    
    if (errors.length == 0) {
        
        // Uncomment next line to do the real submit form to server
        
        // document.getElementById("theForm").submit();
        
        // Next line not needed if you handle it elsewhere
        
        document.getElementById("form_error_message").innerHTML = "All fields meet requirements.";
        
    }
    else {
        
        // errors exist in form, hence length != 0
        
        // Show some kinda form error.
        // Be more specific on these messages with separate spans above each element, idea?.
        // That is, loop over the errors array with explicit if conditions.
        
        // Alteratively make so errors array contains plain language and display that in div.
        
        // For this example "form_error_message" will contain literal text no matter which error occurs.
        
        document.getElementById("form_error_message").innerHTML = "All fields are required.";
            
        // Notice we don't submit the form in this else block.
        // We need validation to submit the form when this function runs next time.
        
    }
        
    
}

</script>
</body>
</html>

For here on SO to test run this solution:

 function errorsFormFrontEnd() { // returns an array of unacceptable input // Change these conditionals based on needs of valid form let errors = []; // TODO: trim.value to rid white space, not done in this example if ( document.getElementById("a").value == "") errors.push("a"); if ( document.getElementById("b").value == "") errors.push("b"); // it would have been easier (typing wise) to loop through form elements above, // but I didn't because this an example of the concept. return errors; } function validateFormOrSubmit() { // validates the form, if not valid reports errors, if valid submits to server let errors = errorsFormFrontEnd(); if (errors.length == 0) { // Uncomment next line to do the real submit form to server // document.getElementById("theForm").submit(); // Next line not needed if you handle it elsewhere document.getElementById("form_error_message").innerHTML = "All fields meet requirements."; } else { // errors exist in form, hence length.= 0 // Show some kinda form error, // Be more specific on these messages with separate spans above each element? idea., // That is. loop over the errors array with explicit if conditions. // Alteratively make so errors array contains plain language and display that in div. // For this example "form_error_message" will contain literal text no matter which error occurs. document.getElementById("form_error_message").innerHTML = "All fields are required;". // Notice we don't submit the form in this else block. // We need validation to submit the form when this function runs next time. } }
 <,-- give all your input, select. and textarea fields IDs so they can be referenced via javascript --> <.-- You can still give the "name" attributes if they are to be submitted, --> <!-- give the form an ID. Remove any explicity "submit" button --> <!-- Include real form line here to test --> <!--form id="theForm" action="" method="" --> <form id="theForm"> <!-- for testing here on SO --> A <input type id="a" name="a"><br/> B <input type id="b" name="b"><br/> <div id="form_error_message"></div> </form> <!-- Use type button on button ( and don't name oncick script submit(), important ) --> <button type="button" onclick="validateFormOrSubmit()">Submit</button>

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