javascript - 使用 javascript 正则表达式匹配验证输入文本字段
问题描述
我想在正则表达式的帮助下验证表单中的 2 个文本字段,但是在循环字段值时出现正则表达式匹配错误 - 在表单提交时出现错误:“未捕获的 TypeError:elem.match 是不是函数”。
我想使用日期格式 dd.mm.yyyy 并且我需要使用文本字段,不能使用日期字段。
HTML:
<form method="post" onsubmit="checkForm(); return false;" action="#">
<input type="text" id="jform0" name="jform0" value="12.12.2020" class="calendar_date">
<input type="text" id="jform1" name="jform1" value="12.12.2020" class="calendar_date">
<input type="submit" value="Posodobi">
</form>
Javascript:
function checkForm() {
// regular expression to match required date format
re = /^\d{1,2}\.\d{1,2}\.\d{4}$/;
document.querySelectorAll(".calendar_date").forEach((elem) => {
if (elem.value != "" && !elem.match(re)) {
alert("Invalid date format: " + elem.value);
elem.focus();
return false;
}
});
alert("All input fields have been validated!");
return true;
}
示例:https ://jsfiddle.net/esedic/4gtn1hw3/13/
任何想法,为什么这不起作用?
解决方案
Use elem.value.match(...)
not elem.match(...)
推荐阅读
- python - Python PLY解析嵌套匹配括号
- typescript - 使用node/express返回上一页时如何维护缓存?
- c++ - 如何为具有 unique_ptr 的类设置析构函数
. 该实例由 make_unique() 创建 - javascript - 触摸设备的迷宫游戏
- javascript - 将 JSON 对象反序列化为其原始类
- opengl - 在 Colab 中使用 Apache TVM 导出 OpenGL 内核代码(X11 相关错误)
- c# - BotFrameworkAdapter.ProcessActivityAsync() 返回 null 或冻结
- elasticsearch - Kibana 仪表板而不是我的应用程序仪表板
- javascript - 如何在firebase数据库中同时将数据存储在两个地方?
- apache-nifi - 设置 nifi.web.http.host 后无法访问 Nifi Web UI