How can I correctly validate a blank field?

Viewed 47

Learning Javascript and trying to work out the best way to validate a text and number fields on a form.

I have the following html form:

>     <form id="captureLegoSets">
        <label for="setName">Lego Set Name</label><br>
        <input class="input input1" type="text" id="setName" name="setName" value=" ">*<br>    
        <label for="setTheme">Set Theme</label><br>
        <input class="input input1" type="text" id="setTheme" name="setTheme" value=" "><br>    
        <label for="setReferenceNumber">Reference Number</label><br>
        <input class="input input1" type="number" id="setReferenceNumber" name="setReferenceNumber" value="0">*<br>
        <label for="setPieceCount">Piece Count</label><br>
        <input class="input input1" type="number" id="setPieceCount" name="setPieceCount" value="0">*<br>
        <br>
        <input class="input input2" type="button" value="Save Set" onclick="captureLegoSets.captureSets()">
        <input class="input input2" type="reset" value="Reset Values">   
    </form>

And attached Javascript (forgive the numerous console.log statements):

    this.captureSets = function(){

    let setName = " ";
    let setTheme = " ";
    let setReferenceNumber = 0;
    let setPieceCount = 0;

    let formFields = document.querySelectorAll(".input1");
    console.log(formFields);
    for (let i=0; i < formFields.length; i++) { 
        console.log(formFields[i]);
        console.log(formFields[i].id);
        console.log(formFields[i].value);
        if ((+document.getElementById(formFields[i].id).value) > 0 | (+document.getElementById(formFields[i].id).length) !== null) {
            console.log(formFields[i].id + " = " + formFields[i].value);
                if(formFields[i].id === "setName"){
                    setName = +document.getElementById(formFields[i].id).value;
                }
                if (formFields[i].id === "setTheme") {
                    setTheme = +document.getElementById(formFields[i].id).value;
                }
                if (formFields[i].id === "setReferenceNumber") {
                    setReferenceNumber = +document.getElementById(formFields[i].id).value;
                }
                if (formFields[i].id === "setPieceCount") {
                    setPieceCount = +document.getElementById(formFields[i].id).value;
                }
                console.log(formFields);                

        } else {
            alert("Please add non-zero values to " + formFields[i].id);
        }
    }

}

The problem I'm experiencing if that the else statement keeps triggering for the text fields if I only check the .value, but if I check the .length, it doesn't trigger at all.

I know I could probably put together a bunch of if statements to check for null, empty and so on, but I'm assuming this would just be poor coding on my part. Is there a better/more concise way of checking for valid inputs?

2 Answers

This may or may not help you, but I think, this is easier for you to check this directly by pattern attribute. You just need to put some regex.

An HTML form with an input field that can contain only three letters (no numbers or special characters):

<form>
     <label for="country_code">Country code:</label>
      <input
       type="text" id="country_code" name="country_code"
       pattern="[A-Za-z]{3}"
       title="Three letter country code">
</form>

https://www.w3schools.com/tags/att_input_pattern.asp

  1. First you have provided default values to all your text fields, which let the following if check resulting in true, since you have provided default values as " " ( " " is not a null )

if ((document.getElementById(formFields[i].id).value > 0) || (document.getElementById(formFields[i].id).length !== null))

  1. In the above expression you have used !== instead of !=
  2. You used | not || for or operation
  3. Remove + before document ( I don't understand why you have added those. Please explain

Hence,

remove default values / check for right conditions in the conditional statements, use a p tag to display all the errors in the bottom. I have provided a simple example of concatenating the errors, you can also use an array to collect the errors. In the best case a separate error text right below each text field is awesome.

HTML

<form id="captureLegoSets">
      <label for="setName">Lego Set Name</label><br />
      <input
        class="input input1"
        type="text"
        id="setName"
        name="setName"
      />*<br />
      <label for="setTheme">Set Theme</label><br />
      <input
        class="input input1"
        type="text"
        id="setTheme"
        name="setTheme"
      /><br />
      <label for="setReferenceNumber">Reference Number</label><br />
      <input
        class="input input1"
        type="number"
        id="setReferenceNumber"
        name="setReferenceNumber"
      />*<br />
      <label for="setPieceCount">Piece Count</label><br />
      <input
        class="input input1"
        type="number"
        id="setPieceCount"
        name="setPieceCount"
      />*<br />
      <br />
      <input
        class="input input2"
        type="button"
        value="Save Set"
        onclick="captureSets()"
      />
      <input class="input input2" type="reset" value="Reset Values" />
    </form>
    <p id="error-text"></p>

JS

captureSets = function () {
        let setName = "";
        let setTheme = "";
        let setReferenceNumber = 0;
        let setPieceCount = 0;
        let errorText = "";
        let formFields = document.querySelectorAll(".input1");

        for (let i = 0; i < formFields.length; i++) {
          if (
            (document.getElementById(formFields[i].id).value > 0) ||
            (document.getElementById(formFields[i].id).length != null)
          ) {
            if (formFields[i].id === "setName") {
              setName = document.getElementById(formFields[i].id).value;
            }
            if (formFields[i].id === "setTheme") {
              setTheme = document.getElementById(formFields[i].id).value;
            }
            if (formFields[i].id === "setReferenceNumber") {
              setReferenceNumber = document.getElementById(
                formFields[i].id
              ).value;
            }
            if (formFields[i].id === "setPieceCount") {
              setPieceCount = document.getElementById(formFields[i].id).value;
            }
          } else {
            alert("Please add non-zero values to " + formFields[i].id);
          }
        }

        if (!setName || setName == "") {
          errorText += " Fill the name text field <br>";
        }
        if (!setPieceCount) {
          errorText += " Fill the piece count text field <br>";
        }
        if (!setTheme || setTheme == "") {
          errorText += " Fill the theme text field <br>";
        }
        if (!setReferenceNumber) {
          errorText += " Fill the reference number text field <br>";
        }

        document.getElementById("error-text").innerHTML = errorText;
      };
Related