Using onBlur with redux-form

Viewed 3172

I am using redux-form 7.0.4, it its working fine other than the following issue.

New user can enter details and existing user can edit details on the same form. I am having issue when existing user edit details and remove data from form field. I want to add check onBlur. If user empty form field and there is blur event I need to fill the initial data inside field.

Restore the initial/server value on blur if field is empty.

Form Field:

<Field
  component={InputField}
  type='text'
  name='registeredName'
  className='form-control'
  required
  placeholder='Registered Business Name*'
/>

InputField Component:

const InputField = ({
  input,
  type,
  placeholder,
  meta: { touched, error, initial }
}) => {
  const onChange = (e) => {
    const val = e.target.value;

    if (type === 'phoneNumber') {
      if (!/^\d+$/.test(val) || String(val).length > 10) {
        return;
      }
    }

    input.onChange(e);
  };


  return (
    <div className='form-group'>
      <input
        {...input}
        onChange={onChange}
        type={type}
        className='form-control'
        placeholder={placeholder}
        value={input.value }
        onBlur={e => {input.value = (!e.target.value) ? initial : e.target.value;}}
      />
      {touched &&
       ((error &&
         <div className='error text-danger'>
           {error}
         </div>
       ))}
    </div>
  );
};
/* eslint-enable */

export default InputField;
0 Answers
Related