首页 > 解决方案 > 使用正则表达式验证数组中的多个邮政编码

问题描述

我正在尝试创建一个针对正则表达式验证邮政编码的函数。用户可以使用一个邮政编码或多个邮政编码。

当我输入一个邮政编码时,它工作正常,但是当输入多个邮政编码时,我只是不确定

这是我的功能

const validatePostcode = (...postcode) => {
  const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
  if (postcode.length > 1) {
    postcode.forEach((item) => {
      console.log(item);
      return postcodeRegex.test(item);
    });
  } else {
    return postcodeRegex.test(postcode);
  }
};

标签: javascriptarrays

解决方案


forEach 方法并不意味着返回任何值:lambda 的返回值被丢弃。这就是你不确定的原因。if... else...也无用。forEach 适用于一个元素的数组。您需要一个接收 lmbda 并返回值的函数。取决于您想要的every,(如果所有邮政编码都匹配,则返回 true,请参阅@ttquang1063750 的回答)或者map(返回一个布尔数组,每个传递的邮政编码一个)或some(如果至少一个邮政编码匹配,则返回 true)

const validatePostcode = (...postcode) => {
  const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
  return postcode.map(item => postcodeRegex.test(item));
};

const validateAtLeastOnePostcode = (...postcode) => {
  const postcodeRegex = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} ?[0-9][A-Z]{2}$/i;
  return postcode.some(item => postcodeRegex.test(item));
};

推荐阅读