Skip to content

Commit

Permalink
Changing cronvalidator to use more robust regular expressions (#129)
Browse files Browse the repository at this point in the history
* Changing cron-validator to use a more streamlined approach with better targeting regexes

Original regexes from https://stackoverflow.com/a/57639657/10139735

Signed-off-by: Adam Mellen <github@mellen.io>

* Consistent formatting - changes look odd in GitHub web view

Signed-off-by: Adam Mellen <github@mellen.io>

* Update cron-validator to reference CRON_REGEXES

* Ensure the whole expression is valid

* Allow empty value

* Rewrite expression to pass all provided examples

---------

Signed-off-by: Adam Mellen <github@mellen.io>
Co-authored-by: Dan Wallis <dan@wallis.nz>
  • Loading branch information
MellenIO and fredden authored May 9, 2023
1 parent 50a4bf7 commit daeb07e
Showing 1 changed file with 27 additions and 14 deletions.
41 changes: 27 additions & 14 deletions view/adminhtml/web/js/cron-validator.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
require([
'Magento_Ui/js/lib/validation/validator',
'jquery',
'mage/translate'
],
function(validator, $) {
validator.addRule(
'cron-validation',
function(value) {
var regex = /^$|(\*|[0-5]?[0-9]|\*\/[0-9]+)\s+(\*|1?[0-9]|2[0-3]|\*\/[0-9]+)\s+(\*|[1-2]?[0-9]|3[0-1]|\*\/[0-9]+)\s+(\*|[0-9]|1[0-2]|\*\/[0-9]+)\s+(\*\/[0-9]+|\*|[0-7])\s*(\*\/[0-9]+|\*|[0-9]+)?/i;
return regex.test(value);
}, $.mage.__('Invalid cron expression. Please try again.')
);
});
require(
[
'Magento_Ui/js/lib/validation/validator',
'jquery',
'mage/translate'
],
function (validator, $) {

const CRON_REGEXES = [
/^(\*|[0-5]?\d(-[0-5]?\d)?(,[0-5]?\d(-[0-5]?\d)?)*)(\/\d+)?\s+(\*|([01]?\d|2[0-3])(-([01]?\d|2[0-3]))?(,([01]?\d|2[0-3])(-([01]?\d|2[0-3]))?)*)(\/\d+)?\s+(\*|([0-2]?\d|3[01])(-([0-2]?\d|3[01]))?(,([0-2]?\d|3[01])(-([0-2]?\d|3[01]))?)*)(\/\d+)?\s+(\*|(0?\d|1[0-2])(-(0?\d|1[0-2]))?(,(0?\d|1[0-2])(-(0?\d|1[0-2]))?)*)(\/\d+)?\s+(\*|0?[0-7](-0?[0-7])?(,0?[0-7](-0?[0-7])?)*)(\/\d+)?$/i, //Regular regex terms - m h dom mon dow
/^@(annually|yearly|monthly|weekly|daily|hourly|reboot)$/i, //Predefined cron macros (non-standard)
/^@every (\d+(ns|us|µs|ms|s|m|h))+$/i, //Other cron macros
];

validator.addRule(
'cron-validation',
function (value) {
if (value === '') {
return true;
}
for (let regex in CRON_REGEXES) {
if (CRON_REGEXES[regex].test(value)) return true;
}
return false;
}, $.mage.__('Invalid cron expression. Please try again.')
);
});

0 comments on commit daeb07e

Please sign in to comment.