我试图用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);

enter image description here

推荐答案

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;
}

Javascript相关问答推荐

我不明白这个react 组件有什么问题

创建私有JS出口

React:未调用useState变量在调试器的事件处理程序中不可用

类型自定义lazy Promise. all

使搜索栏更改语言

如何使覆盖div与可水平滚动的父div相关?

在Vite React库中添加子模块路径

为什么按钮会随浮动属性一起移动?

阿波罗返回的数据错误,但在网络判断器中是正确的

在WordPress中使用带有WPCode的Java代码片段时出现意外令牌错误

为什么我的getAsFile()方法返回空?

基于props 类型的不同props ,根据来自接口的值扩展类型

Reaction Redux&Quot;在派单错误中检测到状态Mutations

JavaScript不重定向配置的PATH

为什么可选参数的顺序会导致问题?

FireBase云函数-函数外部的ENV变量

ngOnChanges仅在第二次调用时才触发

更改agGRID/Reaction中的单元格格式

如何使用Reaction路由导航测试挂钩?

将以前缓存的 Select 器与querySelector()一起使用