Comments (7)
same issue
from resolvers.
Hey @azizur ,
Thanks for the detailed explanation above. We do pass context
into the resolver
. However, for those resolvers in the repo, I would treat them as a black box and you only should apply config and not with context. if you need pass data into resolver, i would do this instead
resolver: (data, context) => {
if (context.xxx) {
yupResolver(validationSchema)(data);
} else {
yupResolver(validationSchema)({...data, test: 'test' });
}
}
from resolvers.
const { handleSubmit, register, errors, setValue, reset } = useForm({
resolver: (data) => yupResolver(validationSchema, { abortEarly: false, context: data })(data)
});
thanks @azizur for your feedback. I think the good thing above is universal and not only applied to yup or potential other schemas. also we will probably running into problem with cache context with above solution.
{ setValidationContext: {a:'user-provided-object'} }) }
we are cashing resolver, so user won't have to cache it manually and context object is mutable.
from resolvers.
@bluebill1049 Before this get released, I was thinking what the API would be?
I have a Yup schema that uses custom validation in a nested object. The custom validation depends on form the data being provided as context. This allows me to use the context object when validating the the object.
According to react-hook-form/react-hook-form#1471. It seems like, you can just do as per your example on there.
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from 'react-hook-form-resolvers';
const SignupSchema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: yupResolver(SignupSchema), // yup, joi and even your own.
});
return (
<>
<form onSubmit={handleSubmit(d => console.log(d))}>
<label>Test</label>
<input name="test" ref={register} />
<input type="submit" />
</form>
</>
);
};
My question is when the resolver is called by resolver: yupResolver(SignupSchema)
. Can we provide the form data as validation context as well?
I guess one could do as per https://github.com/react-hook-form/react-hook-form-resolvers/blob/master/src/yup.ts#L52
const validationConfig = {
passDataAsContext: true // default false
};
const { register, handleSubmit } = useForm({
resolver: yupResolver(SignupSchema, validationConfig), // yup, joi and even your own.
});
With that flag set: yupResolver looks like this:
export const yupResolver = (
validationSchema: any,
config: any = {
abortEarly: false,
context: data // passing the data as context to validator
},
) => async (data: any, _: any = {}, validateAllFieldCriteria = false) => {
try {
return {
values: await validationSchema.validate(data, {
...config,
}),
errors: {},
};
} catch (e) {
return {
values: {},
errors: transformToNestObject(
parseErrorSchema(e, validateAllFieldCriteria),
),
};
}
};
Or is there a better ways to do this?
I am happy to produce a PR to help with this.
from resolvers.
@bluebill1049, Not the nicest API, however this works with (version 0.0.3).
const { handleSubmit, register, errors, setValue, reset } = useForm({
resolver: (data) => yupResolver(validationSchema, { abortEarly: false, context: data })(data)
});
a clean API could be something like:
const { handleSubmit, register, errors, setValue, reset } = useForm({
resolver: yupResolver(validationSchema, { setValidationContext: true })
});
Where setValidationContext
can be a better named yupResolver
's config option that enables config to be { abortEarly: false, context: data }
in https://github.com/react-hook-form/react-hook-form-resolvers/blob/master/src/yup.ts#L52-L54
The value of setValidationContext
can be either a boolean
or an object.
-
If the value of
setValidationContext==true
it will set thecontext
property todata
eg{ abortEarly: false, context: data }
as per Yupmixed.validate(value: any, options?: object)
options. see: https://github.com/jquense/yup#mixedvalidatevalue-any-options-object-promiseany-validationerror -
If the value of
setValidationContext
is an object it will set thecontext
property to that object eg{ abortEarly: false, context:{a:'user-provided-object'} }
const { handleSubmit, register, errors, setValue, reset } = useForm({
resolver: yupResolver(validationSchema, { setValidationContext: {a:'user-provided-object'} })
});
from resolvers.
hey, @azizur I haven't released an updated version just yet, expected to release a v6 RC version this week.
from resolvers.
First RC version is out for both RHF and RHFR
https://github.com/react-hook-form/react-hook-form-resolvers/releases/tag/v0.0.2-rc.0
let me know how did it go. 👍
from resolvers.
Related Issues (20)
- Valibot - Optional not found
- issue: Valibot resolver optional not Found HOT 1
- AJV Resolver - When ajv schema contains `default` for certain properties, `getValues()` returns the form data with properties overwritten
- typescript type error for yupResolver HOT 22
- Not Possible to use Zod omit on schema passed to resolver HOT 1
- Zod continues to throw errors while using async refinements with react hook form when zod resolver mode is set to async HOT 2
- Issue with valibotResolver causing unexpected form submission behavior HOT 3
- typescript problem in AJV resolver HOT 1
- Fields configured as mandatory are not being validated and are ignored.
- errors object creating circular structure with yup resolver
- Zod superRefine does not correctly revalidate the form on change HOT 2
- Issue with Resolvers tranform
- Extend typeboxResolver with additional types; getting "Unknown type" in Visit3
- AJV resolver is async mode is not working
- Support `@effect/schema` HOT 4
- when type of input is radio,valueAsNumber dont work anymore HOT 1
- `Joi` resolver crashes on `File` validation
- When using `classValidatorResolver`, combining `@IsOptional()` with `@Length()` makes the field required
- [Zod]: Resolver does not validate to reflect correct error state without manual form.trigger() HOT 8
- zodResolver / superRefine / useFieldArray: useForm errors are not updated to reflect zodResolver errors HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from resolvers.