0

I have been setting up files to demonstrate form validation to myself. However I've found that the script doesn't check wether or not the name field is valid or not, could someone please tell me where I've went wrong?

<!DOCTYPE html>

<html>

    <head>

        <script>
            function kValForm() {
                var n = document.forms["kForm"]["kName"].value;
                ...
                if( n == null || n == " " || n ="") {
                    alert("Please fill in your name.");
                    return false;
                }
                ...
            }
        </script>

    </head>

    <body>

        <form name="kForm" onsubmit="kValForm()">

            Name: <input type="text" name="kName" placeholder="Khalifa">
            <br/>
            ...
            <br/>
            <input type="submit">

        </form>


    </body>

</html>

The ellipses are removed bits of code that are irrelevant and take up lots of space. But the code above sends the name form even if it's empty, why?

Zunon
  • 137
  • 1
  • 8

3 Answers3

0

You got an error in your if (missing ==)

if( n == null || n == " " || n ="") {


if( n == null || n == " " || n =="") {
yunandtidus
  • 3,847
  • 3
  • 29
  • 42
0

Your form submits because you have to change your onsubmit:

 <form name="kForm" onsubmit="return kValForm()">

this will prompt.

Here is a link to your modified sample that properly shows the alert: http://jsfiddle.net/bmartinelle/dyL4j49j/

(note: you need to fix your string comparison problem too - "==" instead of just one "="

Edit: As suggested above by @Ramachandran Krishnan you can check for an empty string maybe more efficiently as elaborated in this stackoverflow post: How do you check for an empty string in JavaScript?

(note: just if(n) doesn't work)

Community
  • 1
  • 1
Birgit Martinelle
  • 1,869
  • 1
  • 12
  • 9
  • It still seems to skip over the clearly empty name field and send the form when everything other than the name form reaches minimum requirements. – Zunon Sep 22 '14 at 15:34
  • http://jsfiddle.net/bmartinelle/d0o9q5rx/1/ Looks like if(n) isn't enough - I will modify my answer – Birgit Martinelle Sep 22 '14 at 15:48
  • Nevermind, I guess I did something wrongg in the js, copying yours over sooms to have fixed it. Thanks! – Zunon Sep 22 '14 at 15:53
0

please replace it

onsubmit="kValForm()"

by

onsubmit="return kValForm(this);
Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38