mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

Date rules after and after_or_equal incorrect parameter handling #279

Open sebsowter opened 6 years ago

sebsowter commented 6 years ago

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

mikeerickson commented 6 years ago

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

sebsowter commented 6 years ago

@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 ;).

mikeerickson commented 6 years ago

I will get it worked out :)

benfixit commented 5 years ago

@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?

km1790 commented 5 years ago

Any update on above issue??

lukas-pierce commented 4 years ago

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