validatorjs icon indicating copy to clipboard operation
validatorjs copied to clipboard

Date rules after and after_or_equal incorrect parameter handling

Open sebsowter opened this issue 6 years ago • 6 comments

after and after_or_equal rules expect params val and req. They actually receive val1, val2 and req. Date comparisons should be based on val1 and val2. https://github.com/skaterdav85/validatorjs/blob/master/src/rules.js

sebsowter avatar Jul 24 '18 00:07 sebsowter

@sebeynott thank you for the report, I will have a look at this and get it corrected.

mikeerickson avatar Jul 24 '18 02:07 mikeerickson

@mikeerickson welcome. We are using this validator on a large project and are now overriding these rules. We like the use of Laravel style rules as we have a Laravel backend. Would be nice to kill off our overrides though ;).

sebsowter avatar Jul 24 '18 20:07 sebsowter

I will get it worked out :)

mikeerickson avatar Jul 24 '18 21:07 mikeerickson

@mikeerickson I was trying to use the after_or_equal and before_or_equal rules but it kept failing. I took a peek into the rules.js file and spotted the issue. I'd love to contribute or is this issue currently been sorted out?

benfixit avatar Oct 20 '19 19:10 benfixit

Any update on above issue??

km1790 avatar Oct 31 '19 13:10 km1790

Register custom rule with same name, it overrides builtin rule:

const Validator = require('validatorjs');
const isValid = require('date-fns/isValid');
const parseISO = require('date-fns/parseISO');

const isValidDate = date => typeof date === 'string' && isValid(parseISO(date));

// register custom rule
Validator.register('after_or_equal', function (date, params) {
  const val1 = date;
  const val2 = params.split(',')[0];

  if (!isValidDate(val1) || !isValidDate(val2)) return false;

  const inputDate = parseISO(val1)
  const afterDate = parseISO(val2)

  return inputDate.getTime() >= afterDate.getTime();
}, 'The :attribute must be equal or after :after_or_equal.');



// --------------------------- USAGE ---------------------------------------------

const validator = new Validator({ // data
  date: '2019-11-20'
}, { // rules
  date: 'required|string|date|after_or_equal:2019-11-27'
});
 
validator.passes(); // false, because '2019-11-20' is early than '2019-11-27'
validator.fails(); // true

lukas-pierce avatar Nov 27 '19 11:11 lukas-pierce