javascript - 在发送到后端之前验证 JavaScript 上的输入
问题描述
我是编程初学者。我的代码有很多错误,欢迎提供任何帮助。首先,我尝试在将数据发送到后端的 JavaScript 文件上编写一个函数,我在前端发布了一个片段,以帮助可视化我想要实现的目标。
基本上,我想发送一些数据,但在后端接收数据之前,我想验证数据,并向用户发送错误,告知输入字段有什么问题。
Quantity(indivQty) 只能是大于 0 且小于 stockIndivQty 的整数。
发送/保存数据的功能:
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
,不要到达将数据发送到后端的代码。
一个示例如下所示:
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
or upperBound
。但是,出于示例的目的,此处对其进行了演示。
推荐阅读
- android - 如何将文件或外部数据库导入 SQLite android
- json - 在另一个 Laravel 项目中调用一个 Laravel API 路由
- python - Github 使用 shell 脚本下载单个文件
- python - ValueError:尺寸必须相等,但对于输入形状为 [?,3]、[?,3072] 的“loss/output_1_loss/mul”(操作:“Mul”),尺寸必须是 3 和 3072
- python - Python-join两个数据框以查找在相应行中具有不同值的相同行值
- gdscript - Godot 在基础“KinematicBody2D”上获取索引“玩家”无效
- apache-spark - 无法连接到打开的班次容器内的 Spark Web UI
- java - 在主线程中间等待 HTTP 请求
- c - 将 C 中的变量参数传递给 printf / vsprintf
- ruby-on-rails - 如何防止在 Rails 中篡改 URL