horprogs / Just-validate

Modern, simple, lightweight (~5kb gzip) form validation library written in Typescript, with no dependencies (no JQuery!). Support a wide range of predefined rules, async, files, dates validation, custom error messages and styles, localization. Support writing custom rules and plugins.
https://just-validate.dev/
Other
509 stars 92 forks source link

Undefined error message #127

Open artemchiruhin opened 1 year ago

artemchiruhin commented 1 year ago

So, when I try to show errors messages from backend under input after AJAX request by using showErrors method, it renders message correctly, but then I change any input in form and this message changes to "undefined" like string. I found a solution in using resresh method before showErrors, but should it work like that?

horprogs commented 1 year ago

could you please provide some example? https://codesandbox.io/s/just-validate-template-jrv65?file=/index.html

Seems it should work fine https://just-validate.dev/examples#manually-added-errors

artemchiruhin commented 1 year ago

I have this code in registration form class for validation

this.validator
  .addField('#phone-input', [
      {
          rule: 'required',
          errorMessage: 'Поле обязательно для заполнения',
      },
      {
          rule: 'customRegexp',
          value: /^\+7\(\d{3}\)\d{3}-\d{2}-\d{2}$/,
          errorMessage: 'Формат телефона не корректный'
      }
  ])
  .onSuccess(() => this._register());

In register method I make AJAX request and render errors from backend like this

data.errors.forEach(error => {
      this.validator.showErrors({
          [`#${error.customData.field}`]: error.message
      });
  });

But frontend validation breaks Video - https://skrinshoter.ru/vLTZ2ScVlcm?a

horprogs commented 1 year ago

It's better to call showErrors() just once, instead of doing it in a loop. Try this:

const errors = data.errors.reduce((acc, error) => {
    acc[`#${error.customData.field}`] = error.message
    return acc
  }, {})
  this.validator.showErrors(errors)
artemchiruhin commented 1 year ago

It does not work, only calling refresh method before showing errors helps