如果没有输入,如何调用表单有效性事件
Posted
技术标签:
【中文标题】如果没有输入,如何调用表单有效性事件【英文标题】:How to call form validity event if no input is entered 【发布时间】:2022-01-11 13:21:33 【问题描述】:我有一个带引导程序的简单表单,我需要在提交之前对其进行验证。它自动支持无效反馈。看起来是这样的
let forms = document.querySelectorAll(".needs-validation");
var productNameField = document.getElementById("productName");
productNameField.addEventListener("input", function ()
var val = document.getElementById("productName").value;
console.log("not entering here if I don't enter an input", val);
if (!isValidString(val))
productNameField.setCustomValidity("invalid");
else
productNameField.setCustomValidity("");
);
Array.prototype.slice.call(forms).forEach(function (form)
form.addEventListener(
"submit",
function (event)
if (!form.checkValidity())
console.log("not valid");
event.preventDefault();
event.stopPropagation();
console.log("here validation");
form.classList.add("was-validated");
,
false
);
);
<form
action="/products/addProduct"
enctype="multipart/form-data"
class="needs-validation"
novalidate
method="post"
>
<div class="col-md-12 position-relative">
<label for="productName" class="form-label"
>Product Name</label
>
<input
type="text"
name="productName"
id="productName"
class="form-control"
/>
<div class="invalid-feedback">
Please provide a valid Product Name(at least two
characters, no special characters allowed).
</div>
</div>
<div>
<button type="submit" id="savebutton" name="Submit">
Create
</button>
</div>
</form>
现在,当我输入输入时,如果 !validString(由于输入事件监听器),我会立即看到错误。但是如果我只是点击提交按钮,它不会调用 validString 函数。
我该怎么办?
【问题讨论】:
【参考方案1】: const productNameField = document.getElementById("productName");
const isInputValid = function()
return productNameField.value.length > 1;
const updateValidity = function()
if (isInputValid())
productNameField.classList.remove('invalid')
else
productNameField.classList.add('invalid')
productNameField.addEventListener("input", updateValidity);
const forms = document.querySelectorAll(".needs-validation");
Array.prototype.slice.call(forms).forEach(function (form)
form.addEventListener(
"submit",
function (event)
updateValidity();
if (isInputValid())
console.log("validation complete");
form.classList.add("was-validated");
else
console.log("validation failed");
event.preventDefault();
);
);
【讨论】:
以上是关于如果没有输入,如何调用表单有效性事件的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript通过preventDefault()使input[type=text]禁止输入但保留光标
如何在没有单独的单击事件处理程序的情况下处理多个表单提交 [关闭]