GithubHelp home page GithubHelp logo

How to perform async validation? about form HOT 6 CLOSED

tanstack avatar tanstack commented on August 15, 2024
How to perform async validation?

from form.

Comments (6)

marshallswain avatar marshallswain commented on August 15, 2024

I was able to figure out a good solution with the current API. I just created a form field called emailError and used the FormField utility to make a custom hidden input with some async logic. Here's my quick and dirty example:

import { Form, Text, FormField } from 'react-form';

let lastQuery = {email: ''};
function CustomInput ({field, query, method, ...rest}) {

  return (
    <FormField field={field}>
      {({ setValue, getValue, setTouched }) => {
        if (query.email !== lastQuery.email) {
          lastQuery = query;
          setTimeout(() => {
            if (query.email === '[email protected]') {
              setValue('That email is unavailable');
            } else {
              setValue('');
            }
          }, 500);
        }
        return (
          <input
            type='hidden'
            value={getValue()}
          />
        );
      }}
    </FormField>
  );
}

ReactDOM.render(
  <div>
    <div className='container react-form'>
      <h2>Login - React-Form</h2>
      <Form
        onSubmit={(values) => {
          console.log('Success!', values);
        }}
        defaultValues={{
          email: '',
          password: '',
          emailError: ''
        }}
        validate={({ email, password, emailError }) => {
          let validations = {
            email: !email ? 'E-mail address is required' : emailError || null,
            password: !password ? 'Password is required' : null
          };
          return validations;
        }}
      >
        {(props) => {
          let {values, submitForm} = props;
          let query = {
            email: values.email
          };
          return (
            <form onSubmit={submitForm} className='auth-component-form'>
              <Text field='email' placeholder='e-mail address' />
              <Text field='password' type='password' placeholder='password' />
              <CustomInput field='emailError' query={query} />
              <button type='submit'>Submit</button>
            </form>
          );
        }}
      </Form>
    </div>
  </div>
);

from form.

tannerlinsley avatar tannerlinsley commented on August 15, 2024

Interesting approach. Would it be valuable if react-form supported async lifecycle methods? This would be a lot of work, but it could be extremely useful for circumstances like this one.

Imagine returning a promise in the validate method :)

from form.

marshallswain avatar marshallswain commented on August 15, 2024

Built in async support would be nice, possibly. I was studying form.js looking at where it would be useful. Maybe if we could make it possible to specify a Promise (or a function that returns one) for individual validation attributes. The class-level validate method and its recursive utils could keep track of promises and re-run or perform cleanup after a resolve or reject. This would make it so that non-promise validation attributes could continue to update synchronously if an async request runs long. The only thing it wouldn't address that the above example does address is the ability to mix sync and async validations together. It's really nice to get the immediate feedback of the sync validations; keeps the form responsive to user interaction. I'm not sure the amount of effort would be worth the benefits, though. It's definitely something to think about.

Thanks again!

from form.

tannerlinsley avatar tannerlinsley commented on August 15, 2024

Interesting idea indeed. I'm intrigued by the idea of returning a promise for a validation message instead of the whole object. That would allow exactly what you're imagining: mixed validation timing.

It might be simple enough to maintain a promise queue that maps to validation fields as they come in. As those promises resolve, update the view, and also replace them with new ones if the field is changed again.

Thinking of it that way, it doesn't seem like it would be too much work. Are there any other locations in the api that promises would be beneficial?

from form.

derekperkins avatar derekperkins commented on August 15, 2024

Would that affect performance in large forms?

from form.

marshallswain avatar marshallswain commented on August 15, 2024

I doubt it would feel much different using promises, but it more than likely wouldn't be a breaking change. It can be written so that using the current API doesn't run any of the code for Promises.

Are there any other locations in the api that promises would be beneficial?

@tannerlinsley I'll see if I have more feedback after I try to implement the example I posted.

from form.

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.