tkrotoff / react-form-with-constraints

Simple form validation for React
MIT License
126 stars 20 forks source link

How to reset Form? #22

Closed jordan1982 closed 6 years ago

jordan1982 commented 6 years ago

Hi, how I can reset the form and clear all error?

Thank you

tkrotoff commented 6 years ago

Read this StackOverflow thread: Clear and reset form input fields

tkrotoff commented 6 years ago

However the field feedbacks are not reset, I will fix this in the next version

jordan1982 commented 6 years ago

ok, is there a way I can clean up field feedback? Thank you

jordan1982 commented 6 years ago

Waiting for the new version of the component, to clean the error messages we used the updateFields method (calling it for each field). It would be useful to implement a new method that cycles on the fields and clears all errors. It's possible @tkrotoff ? Can I help you?

this.form.fieldsStore.updateField("name", { dirty: false, errors: new Set(), warnings: new Set(), infos: new Set(), validationMessage: "" });

Thank you

tkrotoff commented 6 years ago

calling it for each field

No need, you can do this instead:

  handleReset() {
    for (const fieldName in this.formWithConstraints.fieldsStore.fields) {
      this.formWithConstraints.fieldsStore.updateField(fieldName, {
        dirty: false,
        errors: new Set(),
        warnings: new Set(),
        infos: new Set(),
        validationMessage: ''
      });
    }
    this.formWithConstraints.forceUpdate();
  }

Don't forget also to re-initialize the state (this.setState(this.getMyInitialState())).

In the next version you will have this.formWithConstraints.reset().

Thanks for you feedback.

Edit: better approach.

jordan1982 commented 6 years ago

good job, tell me when new version is aivalable. Thank you @tkrotoff

tkrotoff commented 6 years ago

I've released v0.8.0 There is now a FormWithConstraints.reset() (returns a Promise), see https://github.com/tkrotoff/react-form-with-constraints/blob/v0.8.0/examples/Bootstrap4/App.jsx#L79

Took me quite some time, it's a full rewrite (multiple rewrites actually, to find the good recipe) so a few things have changed due to Async support