javascript

Call custom method on form submit redux form

You can create your own method that can validate and check your form on the form submit in the redux form.

//create a file submit.js and write method to call on form submit
import { SubmissionError } from 'redux-form';

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

function submitMethod(values) {
    return sleep(1200).then(() => { // simulate server latency
        if (!['alex', 'july'].includes(values.firstname)) {
            throw new SubmissionError({
                firstname: 'First name you entered is incorrect',
                _error: 'Not able to find First Name!',
            });
        } else {
            window.alert(`Submitted Object is :\n ${JSON.stringify(values, null, 2)}`);
        }
    });
}

export default submitMethod;

//create a file - MyValidationForm.js and design your form there to call above submitMethod in the form 
import React from 'react'
import { Field, reduxForm } from 'redux-form'
import submitMethod from './submit'

const renderThisInput = ({ input, label, type, meta: { touched, error } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type} />
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)

const MyValidationForm = props => {
  const { error, handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit(submit)}> //Calling - submitMethod here from submit.js
      <Field
        name="firstname"
        type="text"
        component={renderThisInput}
        label="First Name"
      />
      <Field
        name="lastname"
        type="text"
        component={renderThisInput}
        label="Last Name"
      />
      {error && <strong>{error}</strong>}
      <div>
        <button type="submit" disabled={submitting}>
          Check Values
        </button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Rest Form
        </button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'myValidationForm'
})(MyValidationForm)

In the code snippet, we created a method name 'submitMethod' where we are checking the value of firstname if it is not found in the given array, it will show the error message on the form, and if the condition is satisfied. It will show the alert with the object on the page.

Was this helpful?