2

I need to build a cron-validator. This is a cron expression,it means every 30 seconds.

*/30 * * * * *

The task is to show an error if the time is less than 30 seconds. Example: So if I write the following, which means, every 10 seconds,

*/10 * * * * *

It should show an error saying, "Please enter more than 30 seconds". Here is example function, expression is cron expression, limit is in miliseconds, So if I pass 30 second, it should validate 30 seconds.

function cronValidator(expression = '', limit = 30000){}

So far, I have tried this:

function cronValidator(expression = '', limit = 30000) {
  // filter the number of seconds from expression
  const [seconds] = expression.match(/(\d+)/);
  // convert seconds into miliseconds
  const milisecondsInExpression = seconds * 1000;

  if (milisecondsInExpression < limit) {
    console.error(`Please enter more than ${limit / 1000} seconds.`);
  } else {
    console.log('You are good to go.');
  }
}

const cronExp = '*/31 * * * * *';

cronValidator(cronExp, 40000);

but it is not working, cause:

  • The limit or expression can be minutes or hours. Not just seconds. It means normal regex is not enough.
Ashik
  • 2,888
  • 8
  • 28
  • 53

1 Answers1

0

Split the input into whitespace-separated fields, and just validate the first field. And you should only check the frequency if it's in the form */#.

let fields = expression.split(/\s+/);
let seconds = fields[0];
let split_seconds = seconds.match(/^\*\/(\d+)$);
if (split_seconds) {
    let milliseconds = split_seconds[1] * 1000;
    if (milliseconds < limit) {
        console.error(`Please enter more than ${limit / 1000} seconds.`);
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612