vinejs / vine

VineJS is a form data validation library for Node.js
https://vinejs.dev
MIT License
1.1k stars 21 forks source link

Discussion for a new feature - Allow date in format ISO 8601 #65

Open padinko opened 4 months ago

padinko commented 4 months ago

Package version

2.1.0

Describe the bug

It is currently impossible to validate dates in ISO8601 format.

Day.js requires ISO8601 format when using the dayjs(value) function. documentation

but this plugin force to use dayjs(value, formats, true) and there is no format for ISO8601 string in available formats

ISO8601 format is most common format for dates, can we use it in vine date validator please?

Reproduction repo

No response

padinko commented 4 months ago

I created an adonisjs provider to handle ISO8601 dates if anyone needs it:


import vine, { symbols, Vine, VineDate } from '@vinejs/vine';
import { messages } from '@vinejs/vine/defaults';
import dayjs from 'dayjs';

const isIsoDate = vine.createRule((value, _, field) => {
    if (typeof value !== 'string') {
        field.report(messages.date, 'date', field);
        return;
    }

    const dateTime = dayjs(value);
    if (!dateTime.isValid()) {
        field.report(messages.date, 'date', field);
        return;
    }

    field.meta.$value = dateTime;
    field.mutate(dateTime.toDate(), field);
});

class VineDateIso extends VineDate {
    constructor() {
        super(undefined, [isIsoDate()]);
    }

    [symbols.UNIQUE_NAME] = 'vine.dateIso';

    [symbols.IS_OF_TYPE] = (value: any) => {
        if (typeof value !== 'string') {
            return false;
        }

        return dayjs(value).isValid();
    };
}

declare module '@vinejs/vine' {
    interface Vine {
        dateIso(): VineDateIso;
    }
}

export default class VineDateIsoProvider {
    /**
     * The container bindings have booted
     */
    async boot() {
        Vine.macro('dateIso', () => new VineDateIso());
    }
}