Function returning function doesnt work for redux form field-level validation.

69 Views Asked by At

It`s a bit weird behavior, but I cannot actually figure out whats going on with my validation :)

I have a field level validation

export const confirm = (valueToConfirm, message) => (value, allValues) => {
  if (value !== allValues[valueToConfirm]) {
    return message;
  }

  return undefined;
};

And its using like

<Field
  type="email"
  name="confirmEmail"
  component={TextInput}
  validate={[required, email, confirm('email', 'Bla-bla-bla')]}
/>

And thats actually works only in case, when some another validation failed. So if user input correct all fields, and just confirmEmail would not match email - there would not be any validation error!

But if I change validation, so it would not be a function returning function - it works.

export const confirmEmail = (value, allValues) => {
  if (!value || value !== allValues.email) {
    return 'Bla-bla-bla';
  }

  return undefined;
};

P.S. Same for all Field-level validation, for example dynamic minLength validation.

2

There are 2 best solutions below

0
On

I know you are using Redux Field however this is also easily achievable with Vanilla React.

<form>
 <input
                type="text"
                name="username"
                placeholder="name"
                value={this.state.username}
                onChange={this.handleChange}/>
</form>

 handleChange(e) {
   //check for validation here to have real time feedback to user when their 
   inputs match what you're looking for. 

 }
0
On

It looks like the confirm validation function is incorrect. The validation function you're using:

export const confirm = (valueToConfirm, message) => (value, allValues) => {
  if (value !== allValues[valueToConfirm]) {
    return message;
  }

  return undefined;
};

with the arguments you're using:

confirm('email', 'Bla-bla-bla')

means it will always validate. You're validating the value of the email input against the value of the email property in allValues, which is the value the email input. That is:

// value = [email protected]
// allValues = {email: '[email protected]'}
// valueToConfirm = 'email'
// message = 'Bla bla bla'

if (value !== allValues[valueToConfirm]) {
  return 'Bla bla bla';
}

which evaluates to:

if ([email protected] !== [email protected]) {
  return 'Bla bla bla';
}

this conditional will always fail, meaning the validation will pass.