首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript表单验证:自定义错误消息

Javascript表单验证:自定义错误消息
EN

Stack Overflow用户
提问于 2018-07-29 08:52:51
回答 1查看 3.8K关注 0票数 1

https://codepen.io/durja/pen/BPmmyR

我正在尝试使用html中的约束api为表单实现自定义错误消息。下面是我的代码,我面临着一个问题,在输入错误的输入并再次更正后,验证消息仍然显示。我不确定我错过了什么。我甚至尝试使用checkValidity()方法检查有效性,即使输入的模式是正确的,该方法也会返回false。

代码语言:javascript
复制
const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input',e => {
    console.log(e.target.value);
   if(fp.validity.rangeOverflow) {
       fp.setCustomValidity('Custom message: greater than 100 not allowed.');
   }
});

ide.addEventListener('input',e => {
  console.log(e.target.value);
  console.log(ide.checkValidity());
  if(ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  }
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-29 08:57:41

请参阅HTMLSelectElement.setCustomValidity()

HTMLSelectElement.setCustomValidity()方法将选择元素的自定义有效性消息设置为指定的消息。使用空字符串指示元素没有自定义有效性错误。

您当前从未重置过自定义有效性消息,因此只要输入无效,它就会永远保持'Custom message: greater than 100 not allowed.' (或其他元素的其他消息)。插入else语句(如果没有rangeOverflowpatternMismatch),这些语句使用空字符串调用setCustomValidity以清除错误消息,以防在单击按钮时出现错误消息:

代码语言:javascript
复制
const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input', e => {
  if (fp.validity.rangeOverflow) {
    fp.setCustomValidity('Custom message: greater than 100 not allowed.');
  } else {
    fp.setCustomValidity('');
  }
});

ide.addEventListener('input', e => {
  if (ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  } else {
    ide.setCustomValidity('');
  }
})
代码语言:javascript
复制
.u {
  margin-bottom: 15px;
}

.u:invalid {
  border: 2px solid orangered;
}

.u:valid {
  border: 2px solid greenyellow;
}

.btn {
  border: none;
  padding: 10px;
  border-radius: 8px;
  margin-top: 10px;
}

:focus {
  outline-color: gray;
}
代码语言:javascript
复制
<form action="#" method="get">
  <div>
    <label for="ide_pref">Would you prefer webstorm or vscode?</label>
    <input required class="u" type="text" pattern="webstorm|vscode" id="ide_pref" name="ide_pref"><br>
    <label for="quantity">How many licences would you like?</label>
    <input required class="u" type="number" min="1" max="100" id="quantity" name="lic_quantity"><br>
    <button class="btn" type="submit">Submit</button>
  </div>
</form>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51576375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档