Skip to content

Commit

Permalink
fix: form's valid state should be up to date (#475)
Browse files Browse the repository at this point in the history
  • Loading branch information
minosss authored Oct 18, 2023
1 parent d739f2a commit 2b2ed02
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,10 @@ export class FormApi<TFormData, ValidatorType> {
(field) => field?.isValidating,
)

const isFieldsValid = !fieldMetaValues.some((field) =>
isNonEmptyArray(field?.errors),
const isFieldsValid = !fieldMetaValues.some(
(field) =>
field?.errorMap &&
isNonEmptyArray(Object.values(field.errorMap).filter(Boolean)),
)

const isTouched = fieldMetaValues.some((field) => field?.isTouched)
Expand Down
32 changes: 32 additions & 0 deletions packages/form-core/src/tests/FormApi.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { expect } from 'vitest'

import { FormApi } from '../FormApi'
import { FieldApi } from '../FieldApi'

describe('form api', () => {
it('should get default form state', () => {
Expand Down Expand Up @@ -267,4 +268,35 @@ describe('form api', () => {

expect(form.getFieldValue('name')).toEqual('two')
})

it("form's valid state should be work fine", () => {
const form = new FormApi({
defaultValues: {
name: '',
},
})

const field = new FieldApi({
form,
name: 'name',
onChange: (v) => (v.length > 0 ? undefined : 'required'),
})

field.mount()

field.handleChange('one')

expect(form.state.isFieldsValid).toEqual(true)
expect(form.state.canSubmit).toEqual(true)

field.handleChange('')

expect(form.state.isFieldsValid).toEqual(false)
expect(form.state.canSubmit).toEqual(false)

field.handleChange('two')

expect(form.state.isFieldsValid).toEqual(true)
expect(form.state.canSubmit).toEqual(true)
})
})

0 comments on commit 2b2ed02

Please sign in to comment.