8

I would like to have user-defined cron expressions in my program. Are there are validators for cron expressions so that the user cannot insert an invalid cron code?

N.B. I think the cron expression on Quartz.Net has a slight different format than the one used in UNIX. I would like to the Quartz version of it.

disasterkid
  • 6,948
  • 25
  • 94
  • 179

3 Answers3

6

UNIX Cron expressions and Quartz ones are differents. Simply,

  • In Unix
    • (minute, hour, day, month, day_of_week, year)
  • In Quartz
    • (second, minute, hour, day, month, day_of_week, year)

You can use this to know if a Cron expression is correct.

EDIT : Look at CronExpression.ValidateExpression method.

Kraiss
  • 919
  • 7
  • 22
2

The question is aged but now there are more options.

I found useful this new nuget package NCrontab.Advanced that is a good replacement for the older NCrontab adding more features, and should have a more wide range of application.

MauriDev
  • 445
  • 2
  • 8
0

Can use The method CronExpression.IsValidateExpression() with an additional regex validation using regex.

example

public static bool IsValidSchedule(string schedule) {

        var valid = CronExpression.IsValidExpression(schedule);
        // Some expressions are parsed as valid by the above method but they are not valid, like "* * * ? * *&54".
        //In order to avoid such invalid expressions an additional check is required, that is done using the below regex.

        var regex = @"^\s*($|#|\w+\s*=|(\?|\*|(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?(?:,(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?)*)\s+(\?|\*|(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?(?:,(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?)*)\s+(\?|\*|(?:[01]?\d|2[0-3])(?:(?:-|\/|\,)(?:[01]?\d|2[0-3]))?(?:,(?:[01]?\d|2[0-3])(?:(?:-|\/|\,)(?:[01]?\d|2[0-3]))?)*)\s+(\?|\*|(?:0?[1-9]|[12]\d|3[01])(?:(?:-|\/|\,)(?:0?[1-9]|[12]\d|3[01]))?(?:,(?:0?[1-9]|[12]\d|3[01])(?:(?:-|\/|\,)(?:0?[1-9]|[12]\d|3[01]))?)*)\s+(\?|\*|(?:[1-9]|1[012])(?:(?:-|\/|\,)(?:[1-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