javascript - How can I validate inputs against Regex using .every() method?
问题描述
I have a function getSum()
. I have two date inputs and I am trying to validate, before a piece of code is run. I have an if statement and the condition is a .every
on the inputs array. I need to pass in a function which matches BOTH input values to the Regex, before the code is executed.
I'm quite confused.
var sumButton =
document.querySelector(".sumNumbers");
sumButton.addEventListener("click", getSum);
var dateRegEx = /^(19|20)\d{2}-(0\d{1}|1[0-2])-([0-
2]\d{1}|3[0-1])$/;
var removeErrorMsg =
document.querySelectorAll(".resetError");
removeErrorMsg.addEventListener("click", function()
{
document.getElementById("errorMsg").textContent =
"";
})
function getSum() {
let inputs = ['dateInput1', 'dateInput2'];
let outputs = ['result1', 'result2'];
if (inputs.every(function(){
})) {
inputs.forEach(function(input, index) {
const inputValue =
document.getElementById(input).value;
var sum = 0;
for (var i = 0; i < inputValue.length; i++) {
const num = parseInt(inputValue.charAt(i));
if (!isNaN(num)) {
sum += num;
}
}
const total = (sum - 1) % 9 + 1;
document.getElementById(outputs[index]).textContent
= "Your number is: " + total;
});
} else{
document.getElementById("errorMsg").textContent =
"*error* please enter two dates and two names"
}
//
}
解决方案
该every
方法接受一个回调,该回调传递给every
被调用的数组的每个元素,如果回调的所有返回值都是true
,则every
返回true
,否则every
返回false
。
所以你只需要编写一个回调函数来传递给every
它接受数组的单个元素inputs
并返回一个布尔值。要针对正则表达式进行测试,我们可以使用 regextest
方法,true
如果给定的字符串与正则表达式匹配,则返回,false
否则返回。
例如:
function dateIsValid(dateString) {
return dateRegEx.test(dateString);
}
在上下文中:
if (inputs.every(dateIsValid)) {
// ...
}
或者使用内联定义:
if (inputs.every(dateString => dateRegEx.test(dateString))) {
// ...
}
推荐阅读
- elasticsearch - elasticsearch more_like_this 查询不适用于大于 6 的数组
- angular - Gitlab Pipeline作业失败的角度构建
- javascript - 正则表达式匹配以表标签开头的字符串,仅排除警告词
- python - 如何用字典创建华夫饼图?
- html - SVG 无法正确调整 Firefox 和 Edge 中 flexbox 中容器的大小
- python - 视图计数器不会在数据库中增加
- swift - swift中的noHistory等价物,没有以前的视图控制器
- python - 如何在 Azure 中的 python 中使用 Eventhub 和 Storage SDK
- angular - 在更改表单控制角度反应形式之前询问确认警报
- java - JavaDoc中的`.`和`#`有什么区别?