0

I have a form on a website and I am validating it using JS. The issue I have is, after the form has failed validation, the browser clears the data which has been inputted by the user.

I have tried stripping the "submit" type value from the button and submitting the form using JS. My code checks each field individually, keeping count of any issues, and should only submit if the count > 0.

function validateForm()
{
    var errors = 0;
    // if test fails errors++

    if(errors > 0)
    {
        alert("Please correct the following " + errors + " error(s):\n" + errorList);
    return false; // I assumed this would prevent the form submitting
    }
    else
    {
        document.forms[0].submit();
    }
}

The code for my button is

HTML
<button tabindex = "18" id = "submitForm" onclick = "validateForm();">Submit</button>

This is not just restricted to IE, it also occurs on Firefox. It is like the form is being submitted as long as all fields are complete regardless of errors.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • add a new property to the button like this: `type="button"`. And after `validateForm();` add ` return false;`. This line is still for the html button. – node_modules Apr 06 '16 at 13:24

3 Answers3

1

Call the javascript function as onclick = "return ValidateForm();" .

Also if the ValidateForm() return true then the Form will be submitted, so there is no need to write "document.forms[0].submit();". Use following function:

function validateForm()
{
    var errors = 0;
    // if test fails errors++

    if(errors > 0)
    {
        alert("Please correct the following " + errors + " error(s):\n" + errorList);
    return false; // I assumed this would prevent the form submitting
    }
    else
    {
        return true;
    }
}

<input type="submit" value="Submit" tabindex = "18" id = "submitForm" onclick= "return validateForm();" />
Kapil Kshirsagar
  • 282
  • 1
  • 4
  • 19
0

Or you can just do:

function validateForm(event)
{
    var errors = 0;
    // if test fails errors++

    if(errors > 0)
    {
        alert("Please correct the following " + errors + " error(s):\n" + errorList);
        return false; 
    }
    return true

and on the button

<button tabindex = "18" id = "submitForm" onclick = "return validateForm(event);">Submit</button>

but i suggest you to use jQuery for this: jquery submit

Douglas Caina
  • 932
  • 10
  • 8
0

For <button>, the default type is submit, set type to button if you don't want it to submit.

dz902
  • 4,782
  • 38
  • 41