Search code examples
reactjsreduxstatestoreredux-form

how do you make validation in redux-form based on state?


I'd like to get some part of my state in validate function, how can I implement it?

I have component

const TransferMoneyBetweenAcountsForm = ({ handleSubmit }) => {
  const WithdrawMoneyForm = ({ handleSubmit, maxMoneyAmount }) => {
  return (
    <form className="form-inline" onSubmit={handleSubmit}>
      <div className="form-group">
        <Field
          placeholder="Money amount"
          name="moneyAmount"
          component="input"
          className="form-control"
        />
      </div>
      <div className="form-group">
        <Field
          placeholder="confirm transfer"
          name="confirmMoneyTranfer"
          component="button"
          className="btn btn-primary"
        >
          Withdraw money
        </Field>
      </div>
    </form>
  );
};

also I have accountsList in my state:

const initialState = {
  accountsList: [
    {
      id: 1,
      number: 11,
      invoice: 150,
    },
    {
      id: 2,
      number: 22,
      invoice: 300,
    },
  ],
};

And I want to add validation on my moneyAmount field to it be less than total invoice of account. I think a should add to validate function props some part of state, but i don't know where I can do it.


Solution

  • As the docs explain: https://redux-form.com/8.3.0/examples/fieldlevelvalidation/

    you can do a field level validation by passing a validate function to the field.

    <Field
       placeholder="Money amount"
       name="moneyAmount"
       component="input"
       className="form-control"
       validate={(fieldValue, allFormValues, props) => { /* your validation here */ }}
     />