vine icon indicating copy to clipboard operation
vine copied to clipboard

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

Open padinko opened this issue 1 year ago • 1 comments

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 avatar Jul 17 '24 13:07 padinko

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());
    }
}

padinko avatar Jul 17 '24 15:07 padinko