horprogs / just-validate-plugin-date

Other
2 stars 0 forks source link

the plugin not validate correctly #3

Open saiballo opened 6 months ago

saiballo commented 6 months ago

Hello,

I have this config:

validate.addField("#js-birthdate", [ { "rule": "required" }, { "plugin": validatorDate(() => ({ "format": "dd/mm/yyyy" })), "errorMessage": "error" }, ], ``

If I insert: 25/12 I get the error. ok

If I insert 25/12/1 the validation is passed... why? Where I'm wrong? thank you

horprogs commented 6 months ago

Hey, as it turned out there is the issue with date-fns which we use under the hood https://github.com/date-fns/date-fns/issues/2087

They suggested to use some workaround, you could implement your own plugin (take this plugin as an example), it would look something like:

const validateDate =
  (format: string) => (value: PluginValueType, fields: PluginFieldsType) => {
    const isMatchYears = (date, pattern) => {
      const yearsLen = pattern.split('y').length - 1
      if (!yearsLen > 0) return true
      else {
        const yearsIndex = pattern.indexOf('y')
        const afterYears = date.slice(yearsIndex)
        const yearsMatch = afterYears.match(/^.\d+/)
        if (yearsMatch && yearsMatch[0].match(/\d+/)[0].length === yearsLen) return true
        return false
      }
    }

    return isMatchYears(value, format)
  }

And usage:

validate.addField("#js-birthdate", [
{
"rule": "required"
},
{
"plugin": validateDate('dd/mm/yyy'),
"errorMessage": "error"
},
],
saiballo commented 6 months ago

thank you, I hope they will resolve because your plugin is very valid!