发送到后端之前验证JavaScript上的输入 [英] Validating input on JavaScript before sending to the back-end
问题描述
我是编程的初学者.我的代码有很多错误,欢迎任何帮助.首先,我试图在JavaScript文件上编写一个函数,该函数将数据发送到后端,我在前端发布了一个代码段,以帮助可视化我要实现的目标.
I am a beginner in programming. My code has a lot of errors and any help will be welcome. First I'm trying to write a function on the JavaScript file where it is sending the data to the back-end, I have posted a snippet to my front-end to help visualize what I am trying to achieve.
基本上,我想发送一些数据,但是在后端接收数据之前,我想验证数据,并向用户发送错误通知输入字段有问题.
Basically, I want to send some data, but before the back-end receive the data I would like to validate the data, and send an error to the user informing what is wrong with the input field.
Quantity(indivQty)的整数只能大于0且小于stockIndivQty.
Quantity(indivQty) should be ONLY int more than 0 and less than the stockIndivQty.
发送/保存数据的功能:
Function to send/save the data:
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>
推荐答案
您可以使用JavaScript函数parseInt()
和isNaN()
检查值是否为有效数字,然后使用基本的if语句检查是否该数字在给定范围内.
如果不是,则显示一条通知,告知某些值不正确(最好:突出显示不正确的输入字段)和return
,以不到达将数据发送到后端的代码.
You can use the JavaScript functions parseInt()
and isNaN()
to check if a value is a valid number, and then use basic if-statements to check if the number is inside a given range.
If not, then display a notification that some value is incorrect (best: highlight the incorrect input-field) and return
, to not reach the code where you send the data to the back-end.
示例如下:
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;
现在,大多数值不一定需要额外分配给新变量,例如lowerBound
或upperBound
.但是,出于示例的目的,此处进行了演示.
Now, most of the values don't necessarily need an extra assignment to new variables like lowerBound
or upperBound
. However, for the purpose of the example, it is demonstrated here.
这篇关于发送到后端之前验证JavaScript上的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!