首页 > 解决方案 > 使用 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/

任何想法,为什么这不起作用?

标签: javascriptregexvalidation

解决方案


Use elem.value.match(...) not elem.match(...)


推荐阅读