Giter Club home page Giter Club logo

final-form's Introduction

You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Final Form.


πŸ’° Hey there! Do you fancy yourself a javascript expert? Take this quiz and get offers from top tech companies! πŸ’°


🏁 Final Form

Final Form

Backers on Open Collective Sponsors on Open Collective NPM Version NPM Downloads Build Status codecov.io styled with prettier

βœ… Zero dependencies

βœ… Framework agnostic

βœ… Opt-in subscriptions - only update on the state you need!

βœ… πŸ’₯ 5.1k gzipped πŸ’₯


Final Form is sponsored by Sencha.

Comprehensive JS framework and UI components for building enterprise-grade web apps.


πŸ’¬ Give Feedback on Final Form πŸ’¬

In the interest of making 🏁 Final Form the best library it can be, we'd love your thoughts and feedback.

Take a quick survey.


final-form's People

Contributors

adrienharnay avatar alexstroukov avatar alirezavalizade avatar amje avatar andarist avatar andrewmcodes avatar antonvialibri1 avatar arfatsalman avatar arnaudweyts avatar asazernik avatar aviaviavi avatar benhamiltonpro avatar bertho-zero avatar danielnixon avatar dependabot[bot] avatar erikras avatar forbeslindesay avatar gbakernet avatar gertdreyer avatar iamandrewluca avatar imgbot[bot] avatar jedwards1211 avatar mark-raymond avatar michaeldeboey avatar milesj avatar ncphillips avatar rosskevin avatar syynth avatar thiefmaster avatar xxleyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

final-form's Issues

Bug: Async validation should prevent submission

I will use this example https://codesandbox.io/s/wy7z7q5zx5
only change line 37 to 3000 ms for easier debuging.

  1. I type last name Newman and age 27
  2. When I type first name John and within 3000 ms and click submit the form
  3. Then I am able to submit it.

I guess expected behaviour should be for submit to be disabled or wait. Right? I can help to fix it. If we agree that it is a bug.

Cannot submit form after returning an error from onSubmit

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

Hey :) please take a look at this example: https://codesandbox.io/s/mq3opx9vo9.
After submitting a form I return some error from onSubmit handler and display it on the page. The problem is that after setting form error(s), form becomes invalid and I cannot send form again. Even calling form.reset() (although I do not want to reset fields values to their initial ones) doesn't help.

What is the expected behavior?

Don't mark form as invalid when settings submitError/submitErrors

[flow] Update Form/Field Subscription to be sealed

Are you submitting a bug report or a feature request?

bug

What is the current behavior?

FormSubscription | FieldSubscription is currently unsealed using an indexer. It allows anything. It should be changed to match typescript definitions fixed in #66.

Discussed here with @erikras #65 (comment)

What is the expected behavior?

FormSubscription | FieldSubscription are sealed types allowing only known keys

Explicitly setting an input to dirty

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

There does not seem to be an API for setting form fields to dirty.

What is the expected behavior?

The FormAPI currently offers ways to blur, focus, and change fields. However, there is no way to explicitly set a field to dirty. For certain use cases (see example below) this would be very helpful. Alternatively, we could probably achieve the same behavior by manually setting an error on a given field (this is what Formik allows you to do).

Other information

Hi,

We are looking to use React Final Form in our application at work. Evaluating our options and reading the documentation, we couldn't figure out how to address a specific use case.

Say you implement an address lookup with a search field for a post code. Entering the post code will return a partially complete address. One required field is missing.

We populate the form inputs with the address. The house number input field (it's a separate input) remains unchanged. Both the dirty and touched properties are false and hence our error message for that field won't trigger.

The user would expect the lookup to fill out all inputs and it might be difficult for them to see that one specific input in a larger form is still empty.

Is there a way to explicitly set an individual field of the form to dirty in such a case? Looking at the docs, we couldn't find one.

So far we've considered the following alternatives:

  • Focusing on each input when autofilling the form causing them to get touched. Unfortunately, this will case the page to scroll, which we don't want.
  • Setting the empty input to some quirky value other than the initial '' (i.e. undefined). This is really hacky and we'd rather not do it.

I have no code sample as this is a hypothetical question at this point.

Thanks

Validation error do not reset when field unmounted

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

Some validation errors do not reset when field unmounted and there is no fields in current form.

Steps to reproduce:

  1. Open https://codesandbox.io/s/oj8mrzlwx9
  2. Click next
  3. Click previous
  4. Click next
  5. Ensure that error from previous state presented and handleSubmit failed.

What is the expected behavior?

Error should be removed from state when field unmounted

Sandbox Link

https://codesandbox.io/s/oj8mrzlwx9

forked from Wizard Form Example

What's your environment?

Other information

Allow overwriting all form values at once

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Currently FormApi change has a following signature change: (name: string, value: ?any) => void.
Is it possible to change all form values at the same time? I tried change('', formValues), but it doesn't work.

What is the expected behavior?

Passing an empty string to action change should overwrite the whole form values.

What's your environment?

react-final-form: 3.0.2, final-form: 4.0.0

Register fields without having to use the <Field /> component

Are you submitting a bug report or a feature request?

feature request

What is the current behavior?

Currently it would seem that the only way to register a field is to define a named <Field /> component inside a <Form /> component.

I have fields which I wish to update pragmatically. But it seems that I cannot change their values if they are not registered. For example I have something similar to what is below. I am passing <LocationSearch/> to <FormSpy /> so I can access its the change prop. When I try to make the changes inside componentDidUpfate the fields are not updated. If I am to change the 'locationSearch' field though it will work which leads me to think that this is because it is a registered field.

class LocationSearch {
  async componentDidUpdate(prevProps) {
    const { change, input: { value }, values, mutators } = this.props;
    if (value && !shallowEqual(value, prevProps.input.value)) {
      const { address, location } = await getGooglePlaces().getPlaceDetails(value.id);

      // These changes won't work 
      change('location', location);      
      change('address', address);

      // But I if I am to do the following locationSearch will be updated 
      change('locationSearch', address);
      
    }
  }
}

const LocationSearchFormSpy = (props) => (
  <FormSpy
      component={LocationSearch}
  />
)

<Form 
  ...
  initialValues= {{
    address: {},
    location: null,
  }}
  render={({...}) => (
    <form>
      <Field
        name="locationSearch"
        component={LocationSearchFormSpy}
      />
      ...
      </form>
  )}
/>

I have tried using mutators also but have had no luck with them either. Maybe there is a better way of doing this that I am not aware of.

Anyway if you can help me out I'd greatly appreciate it.

Great library btw!

4.0.1 typescript error TS2322 on subscriptions

Are you submitting a bug report or a feature request?

Bug

What is the current behavior?

I introduced changes in #61 that produce typescript errors.

What is the expected behavior?

One example:

error TS2322: Type '{ subscription: { errors: true; values: true; }; children: (form: FormSpyRenderProps) => Element; }' is not assignable to type 'IntrinsicAttributes & FormSpyProps & { children?: ReactNode; }'.
  Type '{ subscription: { errors: true; values: true; }; children: (form: FormSpyRenderProps) => Element; }' is not assignable to type 'FormSpyProps'.
    Types of property 'subscription' are incompatible.
      Type '{ errors: true; values: true; }' is not assignable to type 'FormSubscription'.
        Property 'active' is missing in type '{ errors: true; values: true; }'.

What's your environment?

final-form ^4.0.1
react-final-form ^3.0.2

Other information

I created the problem, I'll PR the fix ASAP. Working on it now. I will probably PR tests to react-final-form as well.

FieldArray validation broken in v3.0.0

Are you submitting a bug report or a feature request?

A bug report

What is the current behavior?

The validation function passed to a field array is never called.
Edit Final Form - Issue #49

What is the expected behavior?

The validation function passed to a field array should be called, and work as in v1.

What's your environment?

{
  "final-form": "3.0.0",
  "final-form-arrays": "1.0.0",
  "react-final-form": "2.0.0",
  "react-final-form-arrays": "1.0.1",
}

Feature Request: async blur validation

Absolutely loving the new lib, especially how easy it is to adopt if you're used to redux-form and want to use components & validations that you've already written. πŸ’― There is one feature I miss though, and I wonder if you'll consider re-implementing.

If I understand correctly, the library supports a single validate function that can either return an object for synchronous validations or a promise if it needs to do async. Unless I have it wrong, I believe the consequence is that async validation will be executed too often. In redux-form it was fairly obvious how to trigger an async validation for a single field only when that field blurs. If similar functionality is possible with this library, I'm unable to find it.

Option to use String instead of Symbol for server-side validation

Are you submitting a bug report or a feature request?

Feature request - option to use String instead of Symbol

What is the current behavior?

I am currently upgrading from redux-form, where I have client and server side validation using the same validation functions.

I have noticed that final-form now uses a Symbol to signify FORM_ERROR and ARRAY_ERROR. Unfortunately the Symbol does not serialise too well to JSON.

var FORM_ERROR = Symbol("FORM_ERROR"); 
var errors = { }; 
errors[FORM_ERROR] = "Server failed"; 
JSON.stringify(errors);

{}

var FORM_ERROR = "FORM_ERROR"; 
var errors = { }; 
errors[FORM_ERROR] = "Server failed"; 
JSON.stringify(errors);

"{"FORM_ERROR":"Server failed"}"

This problem is not super importent, I have a workaround.

Looping the validation errors coming out of express, replacing those two symbols with special strings.
Then on the client doing the opposite replacement before passing the error object back to final-form.

Dependent field-level validation in field arrays

πŸ‘‹ Hey, thanks for this promising, yet already awesome library 🏁 !

Are you submitting a bug report or a feature request?

A feature request

What is the current behavior?

Given the following form values...

{
  offers: [
    {type: 'primary', price: 15, url: ''},
    {type: 'presale', price: 12.5, url: 'http://gettickets.com/my-offer'},
    {type: 'presale', price: 10, url: ''},
  ]
}

...and the requirement that an offer with type "presale" must have an associated URL, it is currently impossible to mark the field offers[2].url as invalid.

What is the expected behavior?

There should be a way to do that, shouldn't it ?
In redux-form there's an escape hatch, since the field name is passed to the validate function:

const validateOfferUrl = (value, allValues, fieldProps, fieldName) => {
  const type = getIn(allValues, fieldName.replace(/\.url$/, '.type'))
  if (!value && type === 'presale') {
    return 'This type of offer requires an URL.'
  }
}

Sandbox Link

A working example w/ redux-form:
Edit redux-form array validation

What's your environment?

{
  "dependencies": {
    "final-form": "^1.3.5",
    "final-form-arrays": "^1.0.0",
    "react-final-form": "^1.2.1",
    "react-final-form-arrays": "^1.0.1"
  }
}

🏁 Thanks !

Form can be submitted when async validations are running

What is the current behavior?

If there's any async validation happening, onSubmit will be called regardless of their status.

What is the expected behavior?

onSubmit shouldn't be called until all validators have resolved. FormState.valid is true even though it might not be true.

Sandbox Link

https://codesandbox.io/s/lv3y8mzjm

What's your environment?

[email protected]

Other information

Failing test

it('should not submit if form is still validating', () => {
  const onSubmit = jest.fn()
  const form = createForm({ onSubmit });

  const username = jest.fn()
  form.registerField('username', username, { error: true }, {
    getValidator: () => () => {
      return new Promise(resolve => resolve('Error'))
    }
  })

  form.submit()
  expect(onSubmit).not.toHaveBeenCalled()
})

Accept initialize value for `reset()`

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

reset takes no options and calls initialize with initial values.

What is the expected behavior?

I've found I need to perform this operation:

initialize(mySuperDefaultValues);
reset();

It would be great if I could instead call reset(mySuperDefaultValues)

In the code, we already call initialize: https://github.com/final-form/final-form/blob/master/src/FinalForm.js#L665-L671

We could just pass through an optional argument which defaults to {}. Easy peasy PR..

Merging of FieldState's `error` and `submitError`

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

FieldState has separate fields for error and submitError and no way to automatically merge them.

What is the expected behavior?

Field should be able to handle merging of the error and submitError automatically, so the components may only handle error.

From the perspective of all of my my projects', "merge" can be defined as "give submitError precedence". That is:

function merge(error, submitError) {
 if (submitError) {
  return submitError;
 }

 return error;
}

I don't really see a case where you would have both a valuation error (error) and a submission error (submitError), so perhaps they could just be one and the same from the get-go.

However, if that's not an option (I realise that it is possible to have both validation and submission errors at the same time), this could be introduced as a non-breaking change by simply allowing a prop like mergeErrors?: boolean, or even mergeErrors?: (validationError: ?any, submissionError: ?any) => resolvedError?: anyβ€”or both.

What's your environment?

This feature does not exist in the lastest release (4.4.0 at the time of writing).

Feature Request: Allow multiple Submit Actions / Validation Conditions

feature request

The standard HTML form submits name and value of the button that triggered the submit. This is a long known and very useful behavior. It allows different processing and/or validation.

i.e.: Two buttons "Create" and "Create and Notify" where the second triggers additional email validation and notification.

<button type="submit" name="myAction" value="doit1">Do it 1</button>
<button type="submit" name="myAction" value="doit2">Do it 2</button>

What is the current behavior?

There is no way to know what action triggered the submit without manually modify the form values or provide different submit handlers or input fields.

What is the expected behavior?

There should be a simple/default way to differentiate between triggering actions/buttons.

form.submit("actionName")
//or 
form.submit({additionalField:'someValue'})
//or 
form.submit.with({additionalField:'someValue'})()

Ror React there could be something like this.

<button type="submit" onClick={handleSubmit.with({additionalField:'someValue'})}>ok</button>

React Native support

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Using Final Form on older versions of android with React Native does not work. I get a runtime error because of the use of for...of loops and Symbol (actually I think these are the same since a Symbol is created during the transpilation of for...of by Babel).

What is the expected behavior?

No runtime error

Sandbox Link

I'm not sure how to do this... maybe with Expo?

What's your environment?

"final-form": "^3.0.0",
"react-native": "0.48.4",
"react-final-form": "^2.1.0",

Other information

Maybe there is a way to build Final Form with other options to make the end result more compatible? Is there a way to configure Rollup to avoid this issue? I tried using a polyfill but couldn't get it to work.

Blur and focus actions

bug report or feature request - hard to tell ;)

What is the current behavior?

When I use blur and focus actions, they affect only active state of a given field. It would be great, if it could be used also to REALLY focus or blur fields, which sometimes is nice to do programmatically. For instance, lets say you have change password form, and a user sets password and repeatPassword fields, and clicks enter which submits the form. On submission success, I reset the form. The problem? Repeat password is still focused, and when it is blurred by any user action, it will trigger this field is required error message. Here, blur('repeatPassword') callled just before reset would fix this, but unfortunately it doesn't work for now.

Optimizing field validation - all fields validate on any change in form value

Are you submitting a bug report or a feature request?

hmmm - not sure - feature?

What is the current behavior?

On change of any value in the form, EVERY field validation fires.

https://github.com/final-form/final-form/blob/master/src/FinalForm.js#L459

What is the expected behavior?

When field X value changes
Then the field X validator is run
And the record validator is run

What's your environment?

yarn list v1.3.2
β”œβ”€ [email protected]
β”œβ”€ [email protected]
β”œβ”€ [email protected]
└─ [email protected]

Rationale

I type one letter into any field, and the following validators fire (some of which are a bit heavier than others):

validate firstName
validate lastName
validate email
validate mobilePhone
validate workPhone
validate homePhone
validate addresses[0].address1
validate addresses[0].address2
validate addresses[0].city
validate addresses[0].stateCode
validate addresses[0].postalCode
validate addresses[1].address1
validate addresses[1].address2
validate addresses[1].city
validate addresses[1].stateCode
validate addresses[1].postalCode

This form feels a tad slow, and I have seemingly addressed re-renders, but have tracked down a massive number of calls to validate.

Here is the log on-load: ``` validate firstName validate lastName validate firstName validate lastName validate email validate firstName validate lastName validate email validate mobilePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate addresses[1].stateCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate addresses[1].stateCode validate addresses[1].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate addresses[1].stateCode validate addresses[1].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate addresses[1].stateCode validate addresses[1].postalCode validate firstName validate lastName validate email validate mobilePhone validate workPhone validate homePhone validate addresses[0].address1 validate addresses[0].address2 validate addresses[0].city validate addresses[0].stateCode validate addresses[0].postalCode validate addresses[1].address1 validate addresses[1].address2 validate addresses[1].city validate addresses[1].stateCode validate addresses[1].postalCode ```

Move to final-form org?

Hey! There are already like 4 packages for final-form, maybe it's a good idea to move to final-form org for better organization, is it planned?

errors lost

Are you submitting a bug report or a feature request?

bug?

What is the current behavior?

Existing validations are lost on form change.

This may be related to the change in #73.

screen recording 2018-01-31 at 10 59 54 am

Note that I have tried this with the async field validation example (with updated dependencies) and it works, so something I'm doing differs from it. I do not yet know what I am doing differently to cause this.

What is the expected behavior?

validations are not lost

Sandbox Link

Working example with latest dependencies https://codesandbox.io/s/wkvl93qyx5

What's your environment?

yarn list --pattern final-form
yarn list v1.3.2
β”œβ”€ [email protected]
β”œβ”€ [email protected]
β”œβ”€ [email protected]
└─ [email protected]

TL;DR

I could not reproduce with example, but it was not doing this yesterday before #73. If you have any guidance as to the potential source of the difference, I'd like to try to boil this down to a reproducible test case. So far, I have had no luck.

Any thoughts @erikras? I'll get back to this after lunch.

hasValidationErrors is true even though there are no errors

Are you submitting a bug report or a feature request?

Bug report.

What is the current behavior?

My form fails to submit because hasValidationErrors is true, yet there are no errors in the state.

screen shot 2018-04-25 at 5 28 53 pm

Shouldn't the undefined fields NOT be included in the errors object?

What is the expected behavior?

It is false for no errors.

What's your environment?

final-form v4.6.1
node 8.9.1
npm 5.6.0

IE11 support - required polyfills

Are you submitting a bug report or a feature request?

Both :)

What is the current behavior?

In IE11, final-form and react-final-form throw an error because Symbol isn't available.

ReferenceError: 'Symbol' is undefined
./node_modules/final-form/dist/final-form.es.js

 377 | });
 378 | 
 379 | //      
> 380 | var FORM_ERROR = Symbol('form-error');
 381 | var version = '4.2.0';
 382 | 
 383 | var tripleEquals = function tripleEquals(a, b) {

What is the expected behavior?

Obvious solution is to include a polyfill for the Symbol object.
However, I think that this should be listed somewhere in the docs. Maybe with a list of additional polyfills that need to be included as well.

Sandbox Link

Simple form demo can be used for testing - https://codesandbox.io/s/q78r2oqq96

What's your environment?

  • final-form@^4.2.0
  • react-final-form@^3.1.0
  • Windows 7, IE11, node@^8.9.1

I can help with enhancing the docs, but before I start, it would be good if you can provide me some insights about the library internals, especially the ES2015+ features that aren't supported in older browsers.

Easier way to access registered fields

Are you submitting a bug report or a feature request?

Feature request.

In my current project, I'm using a custom mutator to set additional field configuration into field.data.config, which works great. The problem is there's no easy way with the current API to access registered fields: form.getRegisteredFields() just returns the names, form.getState() returns form state and not the field objects, form.registerField() returns an unsubscriber and not the field object, form.subscribe() is form state and not field objects, etc.

The only approach I've found is to use a mutator like getFields, which simply returns state.fields, but this seems hacky.

What is the current behavior?

Field objects are abstracted away.

What is the expected behavior?

Being able to access fields with something like form.getFields().

What's your environment?

Final form 4.3.1
Node 8.9.1
NPM 5.6.0

Other information

N/A

Validate only changed field

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Hey :) First thanks for this great library, it is a real pleasure working with it, but let me go to the point. I have a large form containing ~20 fields. Each field has its own validation function passed in form.registerField, so current behaviour is as follows. If I change the value of any field, it will trigger validation of every registered field, which (in my opinion) and in most of my cases is unnecessary, especially when some field may use async validation (via ajax). I would like to kindly ask you to consider changing this behaviour. Perhaps a new option could be added to registerField e.g:

  form.registerField(
  'someField',
  (fieldState) => {
    this.someField = fieldState
  },
  { value: true, valid: true },
  (value) => !!val,
  validateFields?: boolean | Array<string> 
  // if it's false will only trigger validation of that field, 
  // if true will trigger validation of every field, 
  // or if it's an array will validate specified fields 
)

What is the expected behavior?

When field value is updated, only trigger validation function of the updated field

Thank you for looking into this.

warning with peer dependencies

Having the latest of each dependencies installed, I have the following warnings:

warning " > [email protected]" has incorrect peer dependency "final-form@^1.2.0".
warning " > [email protected]" has unmet peer dependency "prop-types@^15.6.0".
warning " > [email protected]" has incorrect peer dependency "final-form@^1.0.0".
warning " > [email protected]" has unmet peer dependency "prop-types@^15.6.0".
warning " > [email protected]" has incorrect peer dependency "final-form@^1.3.0".

Form Submission Error Display

Hi, thanks so much for this library! Looks really nice and minimal.

I'm designing an interaction in which form errors are shown to the user after they attempt to submit a form.

If there are errors, I want the errors to stay on the screen until the next time the user attempts the submission. In other words, I do not want an error to appear/disappear as a user types the text that swaps it from invalid to valid.

This is not currently possible with Final Form as I understand it. If a form field is invalid at the point of one submission, making it valid will wipe away its former invalidness, removing the error display. There is no way to model "this field was previously submitted, and was invalid at that time" for display purposes. submitFailed is not true, because the submit action never happened due to the presence of errors.

Is there a way to solve this problem with Final Form today?

Thanks again!

Once there is a submit error, the field never becomes valid

Are you submitting a bug report or a feature request?

Bug report

What is the current behavior?

I have a form for entering a password. When the form is submitted, I may get an error saying "the password is incorrect" which I return from the onSubmit handler as {password: 'the password is incorrect'}, to indicate that the password field is the one that is incorrect.

Unfortunately, after I do this, the form never becomes "valid" again, even after the value has been edited.

What is the expected behavior?

I thought the error would only be there until I edited the field, at that point, I expected it to return to the valid state again.

What's your environment?

I'm using react-define-form

Separate validation errors and submission errors

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Currently the form/fields have two flags: valid and dirtySinceLastSubmit.

valid returns if the form/field have any error (validation or submission). dirtySinceLastSubmit returns if the form/field was touched since the last submission.

Imagine the following scenario:

  • Form is initialized, validation fails so the form can't be submitted. valid = false so we can use that to disable the submit button, mark the field in red or do something to indicate to the user that something needs to be done.
  • The user completes the form, validation passes. valid = true so we can enable the submit button, mark the fields in green or do something to indicate to the user that he can submit his form.
  • The user submits the form.
  • The values are validated again server-side for some other things and some errors occur.
  • There are some submission errors, so valid is now false. We can disable the button again or mark fields red since there are some errors with the form.
  • The user modifies some fields.
  • The submission errors are not cleared on change, so the valid flag is still false.
  • We use the dirtySinceLastSubmit flag to check if the user modified some things and re-enable the button or mark fields green.

And now's the problem: we can't know if the form/field is invalid because of the submission errors or if some fields don't pass the validation.

So if the user, while modifying to be able to submit again, broke some validation rules. We have no way of knowing.

We could in the form subscribe for all the errors and check if the form is passing validation or not this way, but the whole point of the subscription system is to avoid unnecessary updates, and if you validate fields on change, it means a lot of unnecessary updates.

It's not a really big problem, but it's a bit annoying to not be able to display information correctly to users.

What is the expected behavior?

One great way to solve this would be to separate valid and invalid to have something like passesValidation and passesSubmission so we can differentiate and we don't need to subscribe to the whole form state.

Or just to have a flag validates to tell if the form passes validation or not, and then it would be easy to know why the form is invalid.

I'm not sure how hard it would be to implement something like this though.

Sandbox Link

I'll try to do a quick demo if I get the time.

What's your environment?

final-form v4.2.0
Opera 50 on Windows 10

Pass field metadata to validator

Are you submitting a bug report or a feature request?

What is the current behavior?

What is the expected behavior?

The field validate signature should be:
validate?: (value: ?any, allValues: Object, meta: Object) => ?any since there are a few validations that could benefit from it

Examples:
While composing a required and a unique validations:

New entity form:

  • if the value is empty, it fails required ({ touched: true, dirty: false })
  • if the value is filled and it's not unique, it fails unique ({ touched: true, dirty: true })
  • otherwise, valid ({ touched: true, dirty: true })

Now, an edit-like form, with the same validations:

  • if the value is empty, it fails required ({ touched: true, dirty: false })
  • if the value is filled and it's not unique, it fails unique ({ touched: true, dirty: true })
  • if the value is changed, but it's equal to the original value, do not fail unique ({ touched: true, dirty: false }) (does not work)
  • otherwise, valid ({ touched: true, dirty: true })

It's kind of a poor example, but my point is: The validations API needs more context, having only the value + a set of values is not enough context for more specific validations, or to decouple validations, fields, components, and forms.

Sandbox Link

What's your environment?

Other information

How to not run validation when registerField is called?

Are you submitting a bug report or a feature request?

Feature request?

What is the current behavior?

In my current implementation, fields are registered dynamically when React components mount, instead of being defined upfront. This works, but it seems like validation is run anytime a field is registered (

runValidation(undefined, () => {
).

This is problematic as all fields are immediately marked as invalid upon mount, especially for validators like the following:

function validate(value) {
  if (!value) {
    return 'This field is required';
  }
}

Is there a way to handle this? Or work around it?

What is the expected behavior?

Not run validation on immediate mount/register.

What's your environment?

final-form v4.6.1
node 8.9.1
npm 5.6.0

Error if input name with number

Are you submitting a bug report or a feature request?

If input name attr string with number --> <input name="323412" />, I have error "Cannot set a numeric property on an object".

I think this bug happens, because:

// final-form/src/structure/setIn.js

isNaN("4325243")  ===  false // true

isNaN("string_key")  ===  false // false

Sandbox Link

https://codesandbox.io/s/w2po55mw35

Subscribe to field data changes

Are you submitting a bug report or a feature request?

Feature request

What is the current behavior?

Currently FormSubscription does not support subscribing to field's data changes

What is the expected behavior?

const unsubscribe = form.subscribe(
  formState => {
    console.log(formState.data.myField.myData); // Or some other method to access field data, such as getFieldState('myField').data.myData
  },
  { // FormSubscription: the list of values you want to be updated about
    data: true,
  }
})

What's your environment?

final-form v4.6.1
node 8.9.1
npm 5.7.1

Other information

Not sure if this is the best approach but could be potentially quite useful in case fields have more than one piece of data attached to them, such as Typeaheads which have the input text and the selected values.
This would allow to store the selected values as the field value, and still have access to the input text from the field data.

How do I tell if submit was attempted but validation failed

The behaviour I'm trying to produce is to have the "submit" button enabled, even if all the fields are invalid. Once the user clicks submit, I want to disable the button if there are validation errors. That way I can hide all error messages until touched, but if the user clicks submit, all the errors show up.

I tried submitFailed but that doesn't seem to be set to true unless the form is valid when handleSubmit is called.

Linked fields change

Hi! RFF is amazing and super fast. Thanks!

Can i change linked fields? Or calculated fiels?

I need someone like on one field change, different field change or on one field change multiple different fields calculated and change.

Thanks again!

Cannot post questions to StackOverflow

Are you submitting a bug report or a feature request?

Bug report

What is the current behavior?

Currently there is no final-form tag on StackOverflow. This prevents any users from posting questions there, unless they have the required 1500 reputation to create new tags on the platform.

What is the expected behavior?

The tags should already exist, so users with a lower reputation can ask questions.

Other information

I tried to post my other issue as a question on SO first, but couldn't. Thanks!

Errors are not returned in promise on form submit

Are you submitting a bug report or a feature request?

Technically Feature Request

What is the current behavior?

When calling submit with an async onSubmit method that returns an error, the errors are not available in the resolved promise.

What is the expected behavior?

The errors should be returned (if any) when the promise has resolved.

Sandbox Link

https://codesandbox.io/s/kmll6x2xw7

What's your environment?

node v8.9.3
npm v5.5.1
react-final-form: 3.1.0
final-form: 4.2.0

Other information

I believe a simple, yet probably naΓ―ve fix, would just to simply return the errors in the 'complete' function of the 'submit' method of FinalForm.js.

final-form/src/FinalForm.js

Lines 627 to 649 in 5c0b10a

const complete = (errors: ?Object) => {
formState.submitting = false
if (
errors &&
(Object.keys(errors).length ||
Object.getOwnPropertySymbols(errors).length)
) {
formState.submitFailed = true
formState.submitSucceeded = false
formState.submitErrors = errors
formState.submitError = errors[FORM_ERROR]
} else {
delete formState.submitErrors
delete formState.submitError
formState.submitFailed = false
formState.submitSucceeded = true
}
notifyFormListeners()
notifyFieldListeners()
completeCalled = true
if (resolvePromise) {
resolvePromise()
}

Feature request: Subscription to different fields

Hey there.
I'm coming with a feature request.

We're facing an issue. We need to trigger updates, based on changes in another field.
As far, as we could see, there is no way to trigger field update based on change in another field.

I think, it's not that hard, to implement partial subscriptions for form values.

Examples

Are you submitting a bug report or a feature request?

Documentation feature request

Other information

Thanks for redux form, it's super lib. It's not easy to start with, but examples make dx much better. So, it would be cool, to implement at least all basic cases with final-form as well. Any plans about it? Can contributors just create examples dir or any other way to help?

Allow skip validations on registerField

Are you submitting a bug report or a feature request?

feature request

What is the current behavior?

Now just mounted form already has errors. So every field will be rendered twice when it subscribed to error (default behaviour). It because runValidations called always when field registering
https://github.com/final-form/final-form/blob/master/src/FinalForm.js#L654

What is the expected behavior?

It would be great to have ability control this behaviour with option.

Sandbox Link

https://codesandbox.io/s/3vj02z23zp

In this example we see that initial form already has errors.

What's your environment?

Other information

Final Form throwing cannot read property active of undefined after submit

Getting error from Final Form after submission.

Stacktrace:

final-form.es.js:234 Uncaught (in promise) TypeError: Cannot read property 'active' of undefined
    at publishFieldState (final-form.es.js:234)
    at final-form.es.js:601
    at Array.forEach (<anonymous>)
    at notifyFieldListeners (final-form.es.js:599)
    at final-form.es.js:741
    at runValidation (final-form.es.js:587)
    at Object.initialize (final-form.es.js:740)
    at reset (final-form.es.js:822)
    at <anonymous>
publishFieldState @ final-form.es.js:234
(anonymous) @ final-form.es.js:601
notifyFieldListeners @ final-form.es.js:599
(anonymous) @ final-form.es.js:741
runValidation @ final-form.es.js:587
initialize @ final-form.es.js:740
reset @ final-form.es.js:822
Promise resolved (async)
onSubmit @ Form.js:36
apply @ _apply.js:15
baseInvoke @ _baseInvoke.js:21
apply @ _apply.js:16
(anonymous) @ _overRest.js:32
handleSubmit @ Form.js:122
callCallback @ react-dom.development.js:540
invokeGuardedCallbackDev @ react-dom.development.js:579
invokeGuardedCallback @ react-dom.development.js:436
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:450
executeDispatch @ react-dom.development.js:834
executeDispatchesInOrder @ react-dom.development.js:856
executeDispatchesAndRelease @ react-dom.development.js:954
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:965
forEachAccumulated @ react-dom.development.js:933
processEventQueue @ react-dom.development.js:1105
runEventQueueInBatch @ react-dom.development.js:3600
handleTopLevel @ react-dom.development.js:3609
handleTopLevelImpl @ react-dom.development.js:3340
batchedUpdates @ react-dom.development.js:11066
batchedUpdates @ react-dom.development.js:2323
dispatchEvent @ react-dom.development.js:3414

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.