如果输入的确切数字为300000,则表单将被提交。任何其他小于或大于300000的值都将导致显示错误消息。错误消息应仅在值小于300000时显示。代码中的错误是什么?
document.addEventListener("DOMContentLoaded", function() {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let inputV = document.querySelector('#budget').value.trim();
let budgetRegex = /^3[0-9]{5,}/;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (inputV == "" || !budgetRegex.test(inputV)) {
errorMessage.innerHTML = "Value should be at least 300,000.";
errorMessage.style.display = 'block';
} else {
errorMessage.innerHTML = "";
errorMessage.style.display = 'none';
form.submit();
}
});
});
<form action="https://dragonmm.xyz" method="post">
<div class="contact-box">
<div class="left1"></div>
<div class="right1">
<h2>Start</h2>
<label for="name"></label>
<input id="name" type="text" class="field" placeholder="Name" required>
<label for="email"></label>
<input id="email" type="text" class="field" placeholder="Email" required>
<label for="phone"></label>
<input id="phone" type="text" class="field" placeholder="Phone" required>
<label for="budget"></label>
<input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
<div id="errormsg"></div>
</div>
</div>
<button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</form>
1条答案
按热度按时间yr9zkbsy1#
使用数字输入字段(
type="number"
)。使用字段的min
属性来限制输入(尽管用户仍然可以输入自己的文本)。接下来,将值转换为Number
,以便进行计算。下面是一个最小的示例,使用event delegation。
最后:您也应该始终检查服务器端的值。