0

i know there are other questions like mine but before you mark it as a duplicate could you please read it.

i am trying to validate my html form using javascript. i have done this before in another web page and it worked correctly however i am trying to use the same code for my new page but it does not work.

this is the code:

    function validateForm(form) {
    var valid = true;
    
    if (!form.title.value.length)
    {
     valid = false;
     document.getElementById('titleRequired').style.display = "inline-block";
    }
    else
    {
      document.getElementById('titleRequired').style.display = "none";
    
    }
    
    }
    <form id="form" action="register.php" method="post" onsubmit="return validateForm(this)">
     <h2> create profile: </h2>
     <div>
                
                <label for="fname">First Name</label>
                <input type="text" id="fname" name="fname" placeholder="Given Name">
                <span class="error" id="fNameRequired">first name required</span>
                <span class="error" id="capitalRequired">first letter must be capital</span>
            </div>
           
            <div>
                <input type="submit" value="Submit" name="submit" >
            </div>
    
        </form>

i have more inputs for this form however i am doing it step by step and not sure where i am going wrong. i have this exact same code on another project i worked on with more inputs and it works fine.

the output i am currently getting is: it submits the form as normal even when no text is entered.

Ravi Singh
  • 307
  • 2
  • 13
William Awad
  • 109
  • 8

1 Answers1

0

You're not returning the result of the validation. Add return valid; before the last curly brace to return false or true so the submit handler knows what to do.

  • @Ahmed says Reinstate Monica. That's not a typo it's a missing row. return vali; would be a typo. Besides if the answer to the question are that there's a typo the question aren't supposed to be answered and therefor never resolved? BTW my answere wasn't posted after reading the first comment to pick points but entered at the same time. I just saw not returning anything from a function to a handler as as an error and not a typo. – Mattias Lindblom Jan 09 '20 at 11:46
  • Okay. I apologized – Ahmed Ali Jan 09 '20 at 11:47