Thymeleaf 表单验证:使用 JavaScript 检查输入框是否为空
<form th:action='@{/add}' method='post' onsubmit='return checkForm()'>
<input type='text' name='name' required>
<input type='text' name='age' required>
<input type='text' name='email' required>
<button type='submit'>添加</button>
</form>
<script>
function checkForm() {
var name = document.getElementsByName('name')[0].value;
var age = document.getElementsByName('age')[0].value;
var email = document.getElementsByName('email')[0].value;
if (name === '' || age === '' || email === '') {
alert('请填写完整信息!');
return false; // 阻止表单提交
}
return true; // 提交表单
}
</script>
<p>这里使用了<code>onsubmit</code>事件来调用<code>checkForm()</code>函数进行表单验证,如果有任意一个输入框为空,则弹出提示框并返回<code>false</code>,否则返回<code>true</code>,允许表单提交。</p>
原文地址: https://www.cveoy.top/t/topic/nw0s 著作权归作者所有。请勿转载和采集!