用于时间跟踪的正则表达式验证

克里斯

我正在尝试以 Javascript 在 Jira 中完成的方式验证字符串。我正在尝试复制它在 Jira 中的验证方式。我猜我可以用正则表达式做到这一点,但我不知道怎么做。

用户可以输入格式为“1d 6h 30m”的字符串,表示 1 天 6 小时 30 分钟。我的用例不需要几周的时间。如果用户使用无效字符('d'、'h'、'm' 或 '' 之外的任何字符),我想显示错误。此外,字符串必须用空格分隔持续时间,理想情况下,我想强制用户按降序输入持续时间,这意味着“6h 1d”将无效,因为日子应该排在第一位。此外,用户不必输入所有信息,因此“30m”是有效的。

这是我获取似乎有效的天数、小时数和分钟数的代码。我只需要验证部分的帮助。

let time = '12h 21d 30m'; //example
let times = time.split(' ');
let days = 0;
let hours = 0;
let min = 0;
for(let i = 0; i < times.length; i++) {
    if (times[i].includes('d')){
        days = times[i].split('d')[0];
    }
    if (times[i].includes('h')){
        hours = times[i].split('h')[0];
    }
    if (times[i].includes('m')){
        min = times[i].split('m')[0];
    }
}
console.log(days);
console.log(hours);
console.log(min);

在此处输入图像描述

医学

const INPUT = "12h 21d  30s";

checkTimespanFormat(INPUT);

if (checkTimespanKeysOrder(INPUT, true))
  console.log(`${INPUT} keys order is valid`);
else console.log(`${INPUT} keys order is NOT valid`);
//******************************************************************

/**
 * Ensures that time keys are:
 * - Preceeded by one or two digits
 * - Separated by one or many spaces
 */
function checkTimespanFormat(timespanStr, maltiSpacesSeparation = false) {
  // timespan items must be separated by 1 space
  if (maltiSpacesSeparation) timespanStr = timespanStr.toLowerCase().split(" ");
  // timespan items must be separated by one or many space
  else timespanStr = timespanStr.toLowerCase().split(/ +/);

  // timespan items must be formatted correctly
  timespanStr.forEach((item) => {
    if (!/^\d{1,2}[dhms]$/.test(item)) console.log("invalid", item);
    else console.log("valid", item);
  });
}

/**
 * Validates:
 * - Keys order
 * - Duplicate keys
 */
function checkTimespanKeysOrder(timespanStr) {
  const ORDER = ["d", "h", "m", "s"];

  let timeKeysOrder = timespanStr
    .replace(/[^dhms]/g, "") // Removing non time keys characters
    .split("") // toArray
    .map((char) => {
      return ORDER.indexOf(char); // Getting the order of time keys
    });

  for (i = 0; i < timeKeysOrder.length - 1; i++)
    if (timeKeysOrder.at(i) >= timeKeysOrder.at(i + 1)) return false;
  return true;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章