Giter VIP home page Giter VIP logo

Comments (7)

AlinDev avatar AlinDev commented on May 13, 2024 4

same issue

from resolvers.

bluebill1049 avatar bluebill1049 commented on May 13, 2024 2

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.

bluebill1049 avatar bluebill1049 commented on May 13, 2024 2
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.

azizur avatar azizur commented on May 13, 2024 1

@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.

azizur avatar azizur commented on May 13, 2024 1

@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.

  1. If the value of setValidationContext==true it will set the context property to data eg { abortEarly: false, context: data } as per Yup mixed.validate(value: any, options?: object) options. see: https://github.com/jquense/yup#mixedvalidatevalue-any-options-object-promiseany-validationerror

  2. If the value of setValidationContext is an object it will set the context 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.

bluebill1049 avatar bluebill1049 commented on May 13, 2024

hey, @azizur I haven't released an updated version just yet, expected to release a v6 RC version this week.

from resolvers.

bluebill1049 avatar bluebill1049 commented on May 13, 2024

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)

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.