1

I have a form and I am doing some form validation using JavaScript.

function validate() {
    let arr = [];
    arr[0] = form.name ;
    arr[1] = form.mobNumber ;
    arr[2] = form.email ;
    arr[3] = form.query ;
    for (let num = 0; num < arr.length; num++){
        if (arr[num].value == ""){
        arr[num].placeholder = "This field is mandatory";
        arr[num].style.backgroundColor = "rgba(0, 0, 255, 0.1)";
        arr[num].classList.add('redPlaceholder');
        return false;
        }
    }
}
.redPlaceholder::placeholder {
    color: red;
    font-style: italic;
    font-family: 'Roboto' sans-serif;
}
<form name="form" method="post" netlify id="form"  onsubmit="return validate()" >
<input type="text" name="name" placeholder="Name"><br>
<input type="email" name="email" placeholder="E-mail"><br>
<input type="number" name="mobNunber" placeholder="Contact Number"><br>
<textarea name="query" placeholder="Your Query" rows="5"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

In the js part, I have an empty array and later add input fields of the form by accessing them through their name. In the for loop I am checking if each of the input field is filled or not. If not, then I have some code to execute.That code block is running perfectly.

The problem is that when I click submit button with all fields empty, the code in the for loop runs only once - for the first input field. I think that there is some problem with the loop though I have checked the syntax several times.

Praneet Dixit
  • 1,393
  • 9
  • 25
  • 1
    There's a `return` statement in the `if` block, which makes the function terminate immediately. – John Gordon Jun 24 '20 at 15:40
  • @JohnGordon I am using return statement so that the form is not submitted (as per my knowledge). – Praneet Dixit Jun 24 '20 at 15:42
  • I understand that. You should wait to return false until after you have checked _all_ the values. As it is, you're returning false on the _first_ blank value. – John Gordon Jun 24 '20 at 15:44
  • Add `var pass=true` before the `for` loop, and set if to `false` inside the `if` statement. And remove the `return` from withing the loop. After the loop, if `!pass` then `return false;`. – iAmOren Jun 24 '20 at 19:27

2 Answers2

1

In the html, you gave the mobilenumber input the name of mobNunber but the javascript looks for mobNumber so I fixed that. Simply checking if arr.length == num to return false during one of these incompleted inputs did not work so I made a variable that is ticked if one of the inputs was not filled in to return false after the for loop ends. I also added arr[num].style.backgroundColor = "transparent"; so if the user fails to fill in an input, the background won't always stay as that purple-ish color even after filling out the input.

function validate() {

    let err = false;
    let arr = [];
    arr[0] = form.name ;
    arr[1] = form.mobNumber ;
    arr[2] = form.email ;
    arr[3] = form.query ;
    for (let num = 0; num < arr.length; num++){
        if (arr[num].value == ""){
        arr[num].placeholder = "This field is mandatory";
        arr[num].style.backgroundColor = "rgba(0, 0, 255, 0.1)";
        arr[num].classList.add('redPlaceholder');
                err = true;

        }
        else{
         arr[num].style.backgroundColor = "transparent";
        }
    }
        if (err){
        return false;
        }
    console.log(arr[1] + "test")
}
.redPlaceholder::placeholder {
    color: red;
    font-style: italic;
    font-family: 'Roboto' sans-serif;
}
<form name="form" method="post" netlify id="form"  onsubmit="return validate()" >
<input type="text" name="name" placeholder="Name"><br>
<input type="email" name="email" placeholder="E-mail"><br>
<input type="number" name="mobNumber" placeholder="Contact Number"><br>
<textarea name="query" placeholder="Your Query" rows="5"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

Edit: Instead of making a variable, can simply add event to the function when it is called. onsubmit="return validate(event)" and use e to represnt that when the function actually runs function validate(e) and if the for loop detects that one of the values is equal to zero, you can use the function e.preventDefault() to stop the form from submitting. Example here: https://jsfiddle.net/nukeboy212/vskt8epj/2/.

SirSpeciam
  • 169
  • 10
  • Also if you have any control of the backend here, it would be a good idea to make sure that these inputs are actually filled out as someone can just inspect element and delete the javascript. – SirSpeciam Jun 24 '20 at 16:08
1

I would utilize preventDefault which will stop the form from submitting, allowing you to run what you need to and then telling the form to submit when you are actually ready.

Taken from this answer.

function validate(e) {
  e.preventDefault();

  // Form stuff here
}

And update your form submit to:

<form name="form" method="post" netlify id="form" onsubmit="return validate(event)" >
nihiser
  • 604
  • 1
  • 15
  • 28
  • Another answer I believe is to use `e.preventDefault()` in the for loop if one of the values equalts to "". Ill update my answer to do that. – SirSpeciam Jun 24 '20 at 16:51
  • @SirSpeciam Sure, ultimately placement doesn't really matter. But I feel most will put it at the very beginning of a function as a common practice. Found this: https://stackoverflow.com/a/4476994/779600 – nihiser Jun 24 '20 at 17:00
  • In this case it does because the person here wants the form to submit normally if the inputs are filled in correctly and if you were to place `preventDefault()` in the begining you would have to resubmit right after with another function when instead you could just use `preventDefault()` only when there is something wrong. "The simplest solution is just to not call e.preventDefault() unless validation actually fails." - https://stackoverflow.com/questions/22363838/submit-form-after-calling-e-preventdefault/22363966 – SirSpeciam Jun 24 '20 at 17:07