Formik: Field-level validation not working when using `useField` hook

Created on 4 Jul 2019  路  10Comments  路  Source: formium/formik

馃悰 Bug report

Current Behavior

When using the useField hook, field-level validation using the validate property doesn't work.

const [field] = useField({ name, validate: () => 'not good' });

Expected behavior

The validate prop should work just like its Field counterpart.

Reproducible example

https://codesandbox.io/embed/formik-codesandbox-template-p5zc1

Suggested solution(s)

Manually registering the validate function does the trick for me:

useEffect(() => {
  registerField(name, {
    validate: () => 'not good'
  });

  return () => unregisterField(name);
}, [name, registerField, unregisterField]);

Your environment

| Software | Version(s) |
| ---------------- | ---------- |
| Formik | 2.0.1-rc.9
| React | 16.8.6
| TypeScript | 3.5.2
| Browser | Chrome 75
| npm/Yarn | npm
| Operating System | Ubuntu 19.04

Field Bug

Most helpful comment

Why is this behavior not documented here?

I ran into this page by searching how to do field-level validation using hooks.

All 10 comments

Ahh yes, good catch

On that point, I think it makes sense to register field only if validate function is specified. Or is there some other plan for a field registry besides validation?

This is fixed by https://github.com/jaredpalmer/formik/pull/1699, released in v2.0.1-rc.13

This is fixed by #1699, released in v2.0.1-rc.13

Doesn't seem to be fixed still in 2.1.4 :'(

@avetisk this works fine for me in v2.1.4. Are you able to reproduce in CodeSandbox?

@avetisk this works fine for me in v2.1.4. Are you able to reproduce in CodeSandbox?

I moved back to RFF, but I still tried to recreate the issue on CodeSandbox and couldn't, so I guess I missed something there in my code.

So no worries, it works fine! :)

https://codesandbox.io/s/infallible-flower-hf2ur

Awesome, @bummey please have a look and see if this fixes your issue. Thanks!

Works fine now, thanks!

Why is this behavior not documented here?

I ran into this page by searching how to do field-level validation using hooks.

@mordechaim you're free to open a PR to update the documentation

Was this page helpful?
0 / 5 - 0 ratings

Related issues

emartini picture emartini  路  3Comments

PeerHartmann picture PeerHartmann  路  3Comments

najisawas picture najisawas  路  3Comments

dearcodes picture dearcodes  路  3Comments

Jucesr picture Jucesr  路  3Comments