Convalida dell'input su JavaScript prima dell'invio al back-end

Nov 09 2020

Sono un principiante nella programmazione. Il mio codice ha molti errori e qualsiasi aiuto sarà il benvenuto. Per prima cosa sto cercando di scrivere una funzione sul file JavaScript in cui invia i dati al back-end, ho pubblicato uno snippet sul mio front-end per aiutare a visualizzare ciò che sto cercando di ottenere.

Fondamentalmente, voglio inviare alcuni dati, ma prima che il back-end riceva i dati, vorrei convalidare i dati e inviare un errore all'utente informando che cosa non va nel campo di input.

La quantità (indivQty) deve essere SOLO int maggiore di 0 e minore di stockIndivQty.

Funzione per inviare / salvare i dati:

        async function saveTransfer(){

    //ID (inventorylocation table)
    let invLocId = document.querySelector('#itemID span').textContent;
    console.log('invLocId: '+invLocId);
    // Item SKU
    let customSku = document.querySelector('#sku span').textContent;
    console.log('itemSku: '+customSku);
    // Type
    let invType = document.querySelector('#type span').textContent;
    console.log('type: '+invType);
    // InvID
    let invId = document.querySelector('#invID span').textContent;
    console.log('Inventory ID: '+invId);
    let stockIndivQty = document.querySelector('#indivQty span').textContent;

    let trs = document.querySelectorAll('.rows .row');
    let locations = [];

    for(let tr of trs) {
        let location = {};
        location.indivQty =  tr.querySelector('.quantity').value;
        location.locationName =  tr.querySelector('.input-location').value;
        locations.push(location);
    }
    console.log('locations: '+locations);

    let formData = new FormData();
    formData.append('invLocId', invLocId);
    formData.append('customSku', customSku);
    formData.append('locations', JSON.stringify(locations));
    formData.append('invType', invType);
    formData.append('invId', invId);

    let response = await fetch(apiServer+'itemTransferBay/update', {method: 'POST', headers: {'DC-Access-Token': page.userToken}, body: formData});
    let responseData = await response.json();

    if (!response.ok || responseData.result != 'success') {     
        window.alert('ERROR');
    } else {
        window.alert('teste');
        location.reload();
            }
}

window.addEventListener("load", () => {
  let elTotalQuantity = document.querySelector("#totalqty");
  let totalQuantity = parseInt(elTotalQuantity.innerHTML);
  
  function getSumOfRows() {
    let sum = 0;
    for (let input of document.querySelectorAll("form .row > input.quantity"))
      sum += parseInt(input.value);
    return sum;
  }
  function updateTotalQuantity() {
      elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
  }
  
  function appendNewRow() {
    let row = document.createElement("div");
    row.classList.add("row");
    let child;
    
    // input.quantity
    let input = document.createElement("input");
    input.classList.add("quantity");
    input.value = "0";
    input.setAttribute("readonly", "");
    input.setAttribute("type", "text");
    row.append(input);
    
    // button.increment
    child = document.createElement("button");
    child.classList.add("increment");
    child.innerHTML = "+";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      if (getSumOfRows() >= totalQuantity) return;
      input.value++;
      updateTotalQuantity();
    });
    row.append(child);
    
    // button.increment
    child = document.createElement("button");
    child.classList.add("decrement");
    child.innerHTML = "-";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      if (input.value <= 0) return;
      input.value--;
      updateTotalQuantity();
    });
    row.append(child);
    // label.location
    child = document.createElement("label");
    child.classList.add("location-label");
    child.innerHTML = "Location: ";
    row.append(child);

    // input.location
    let input2 = document.createElement("input");
    input2.classList.add("input-location");
    input2.value = "";
    input2.setAttribute("type", "text");
    row.append(input2);
    // button.remove-row
    child = document.createElement("button");
    child.classList.add("remove-row");
    child.innerHTML = "Remove";
    child.setAttribute("type", "button");
    child.addEventListener("click", () => {
      row.remove();
      updateTotalQuantity();
    });
    row.append(child);
    
    document.querySelector("form .rows").append(row);
  }
  
  document.querySelector("form .add-row").addEventListener("click", () => appendNewRow());
  
  appendNewRow();
});
<form>
  <label>Total Quantity: <span id="totalqty">10</span></label>
  <br>
  <div class="rows">
  </div>
  <button type="button" class="add-row">Add new row</button>
</form>

Risposte

1 OskarGrosser Nov 10 2020 at 09:49

È possibile utilizzare le funzioni JavaScript parseInt()e isNaN()per verificare se un valore è un numero valido, quindi utilizzare le istruzioni if ​​di base per verificare se il numero è all'interno di un determinato intervallo.
In caso contrario, visualizza una notifica che indica che un valore non è corretto (migliore: evidenzia il campo di input errato) e return, per non raggiungere il codice in cui invii i dati al back-end.

Un esempio potrebbe essere questo:

let valueFromString = parseInt("10");
if (isNaN(valueFromString)) valueFromString = 0; // Define default value

let lowerBound = 0;
let upperBound = 20;

// Checking if valueFromString is of range [lowerBound, upperBound]; if not, 'return;'
if (valueFromString < lowerBound || valueFromString > upperBound) return;

Ora, la maggior parte dei valori non richiede necessariamente un'assegnazione extra a nuove variabili come lowerBoundo upperBound. Tuttavia, ai fini dell'esempio, è dimostrato qui.