首页 > 解决方案 > 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"
}

// 
}

标签: javascripthtmlcssregex

解决方案


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))) {
    // ...
}

推荐阅读