imbrn/v8n

Date validation

rightaway opened this issue · 2 comments

A very useful rule would be to provide date validation, where you could specify the pattern of a string to see if it's a valid date, for example v8n().date('YYYYMMDDHHMMSS').test('20180817111111)., and existing rules like lessThan, greaterThan, etc could work with it to verify whether it's older or newer than a specified date. Also isPast and isFuture to specify if a date is in the past or future.

imbrn commented

Hey @rightaway, thank you for your suggestion.

You can achieve pattern validation by using the pattern rule, like this:

v8n().pattern(/[0-9]{4}-[0-9]{2}-[0-9]{2}/).test("2018-08-18"); // true

And about adding functions like isPast and isFuture, and making comparison functions like lessThan and greaterThan to work with dates will make the library very tied to the date validations scope.

v8n is very easy to extend and make customizations for working with all use cases with very little work. You can easily construct a module for your use case with just a few lines. Take a look here: https://imbrn.github.io/v8n/Extending.html

Maybe this is a good chance for us to start sharing scoped specificy validations in separated modules (or projects).

Dates are a very complex construct due to their differing formats. I'd suggest creating your own rules with something like moment.js or the newer luxon. Here's your isFuture rule based on luxon for example:

import { DateTime } from 'luxon';

v8n.extend({
  isFuture: () => value => value > DateTime.local(),
});

v8n().isFuture().test(DateTime.fromISO("2080-03-12")); // true

It's really straightforward. I reckon introducing a date library into the core of v8n would be way too heavy. So something like the above will probably serve you just fine.