我在设置自定义警告消息时正在进行客户端表单验证,但即使输入中填充了名称,也会显示相同的弹出消息。
例如,我有一个输入字段来获取下面代码的用户名:
<form id="form" name="contactForm" method="post" action="php/formulario_contactos.php">
<div>
<label for="name">Your name</label>
<input type="text" id="name" name="name" required="">
</div>
<div>
<label for="mail">Your email</label>
<input type="email" id="mail" name="user_mail" required="">
</div>
<div>
<label for="topic">Select Topic</label>
<select id="topic" name="topic" required="">
<option selected disabled hidden value="">Choose a Topic</option>
<option value="link">Site Link</option>
<option value="copyright">Copyright</option>
<option value="errors">Site/Article errors</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
</div>
<div>
<label for="msg">Your message</label>
<textarea id="msg" name="user_message" required=""></textarea>
</div>
<div class="button">
<button type="submit">Submit</button>
</div>
</form>
我编写了下面的javascript代码,将默认浏览器错误消息更改为以下内容:
var inputName = document.getElementById('name');
var form = document.getElementById('form');
form.onsubmit = validateForm();
function validateForm() {
if(inputName.value === ""){
inputName.setCustomValidity("Name is required");
return false;
} else {
inputName.setCustomValidty("");
}
}
我做错了什么?
答案 0 :(得分:1)
您的JavaScript中存在导致验证中断的两个问题:
validateForm
函数在页面加载时运行,而不是在用户提交表单时运行。我已在修订的事件处理程序中添加了解决此问题的setCustomValidty
应为setCustomValidity
以下代码修复了这些问题。
HTML:
<form id="form" name="contactForm" method="post" action="php/formulario_contactos.php">
<div>
<label for="name">Your name</label>
<input type="text" id="name" name="name" required="">
</div>
<div>
<label for="mail">Your email</label>
<input type="email" id="mail" name="user_mail" required="">
</div>
<div>
<label for="topic">Select Topic</label>
<select id="topic" name="topic" required="">
<option selected disabled hidden value="">Choose a Topic</option>
<option value="link">Site Link</option>
<option value="copyright">Copyright</option>
<option value="errors">Site/Article errors</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
</div>
<div>
<label for="msg">Your message</label>
<textarea id="msg" name="user_message" required=""></textarea>
</div>
<div class="button">
<button id="submit" type="submit">Submit</button>
</div>
</form>
JavaScript的:
var inputName = document.getElementById('name');
var form = document.getElementById('form');
var submitButton = document.getElementById("submit");
submitButton.onclick = function () { validateForm(); };
function validateForm() {
if(inputName.value === ""){
inputName.setCustomValidity("Name is required");
return false;
} else {
inputName.setCustomValidity("");
}
}