我有一个表格,如小提琴https://jsfiddle.net/vrn7zx5h/3/所示,我要在其中同时同时显示所有未填写的必填字段的警告标志“请填写此字段”。
我在SO上找到了答案(如下所示),但是我不确定如何与小提琴整合。
function checkName(val){
if(/^[^-\s][\w\s]+$/.test(val)){
return true;
}else{
if(val.length != 0){
return false;
}
}
}
问题陈述:
我想知道我应该在小提琴中进行哪些更改,以便上面粘贴的 SO答案与小提琴一起使用。
答案 0 :(得分:0)
这是一个JS小提琴,可一次显示所有错误。这只是准系统,并不花哨。您需要自己动手制作。我还通过form标签中的novalidate
禁用了内置验证器。
https://jsfiddle.net/6kxc9hmq/1/
仅供参考:如果输入现在满足条件,我也没有添加功能以在下次运行时隐藏错误消息。
基本上,我在表单上附加了一个提交事件处理程序,如果验证程序返回false,我告诉表单不要提交。仅适用于IE9 +(我认为),所有其他浏览器通常都可以使用此方法。验证器基本上只是检查输入的值是否满足我指定的条件。
document.getElementById('form').addEventListener('submit', function(e) {
if(!validate())
e.preventDefault();
});
答案 1 :(得分:0)
如果我理解您的意思,我想应该是这样
<form action="">
Username: <input type="text" name="usrname">
Password: <input type="password" name="Password">
<input type="submit">
</form>
<p><strong>Note:</strong> The required attribute of the input tag is not
supported in Internet Explorer 9 and earlier versions.</p>
<script>
// append the listeners
document.forms[0].addEventListener('submit', function(evt){
if([
checkName(this.querySelector('[name="usrname"')),
checkName(this.querySelector('[name="Password"'))
].some((v)=>v)) {
evt.preventDefault()
}
})
// check is empty, then notify
function checkName(element){
// if you just have to check if is empty, this is enough
if(element.value) {
return
}
notify(element)
return true
}
// print the message
function notify(element) {
if(element.nextElementSibling.classList.contains('notify')) {
return;
}
element.parentNode.insertBefore(
Object.assign(document.createElement('p'),
{
className: 'notify',
innerHTML: 'Please fill out this field for all empty and required fields'
}
), element.nextSibling)
}
</script>
答案 2 :(得分:0)
在表单中,在每个输入元素之后添加空div。您可以在验证中有条件地在div中显示消息。例如if(name ==‘’){div.innerHTML =‘请输入您的名字’}
答案 3 :(得分:0)
必填属性 将所需的属性添加到您的窗体。
必填属性告诉浏览器仅在填写有问题的字段时提交表单。显然,这意味着该字段不能为空,但这还意味着,根据其他属性或字段的类型,将仅接受某些类型的值。