2
votes

I am using Formik with yup validations and Its working perfectly. What I'm trying to do is I want to integrate cleavejs for formatting like numerical format. The problem is when my formik Field change to Cleave then the format is working however it doesn't validate the form. But when I change to input to Field the validations is working but the formatting doesn't work. How can i pass Cleave js format into my Formik Field without changing Field to Cleave Hers my code.

I tried to follow the cleave js documentation and its work but it doesn't work on my validation. According to cleave js documentation change input to Cleave but I'm using Field to work my formik yup validations.

import React, { useState, useEffect, useRef } from 'react'
import ReactDOM from 'react-dom'
import { Formik, Field } from 'formik'

import {getvalidations} from './app' 
import Cleave from 'cleave.js/react'



export default function New (props){
const [state, setValue] = useState({
    rate:'',
});

return(
    <Formik
        initialValues={state}
        validationSchema={getvalidations}
        onSubmit={handleSubmit}
        render={formProps => {

        const { values, isSubmitting, errors, handleChange, handleBlur, handleSubmit, touched } = formProps

        return (
            <React.Fragment>
               div className="field">
                   <label className="label">Rate</label>
                   <div className="control">
                      <Field 
                          name="rate"
                          type="text" 
                          onChange={handleChange}
                          options={{numerical: true}}                                     
                            className={(() => {                                         
                              return touched.rate && errors.rate 
                              ? 'is-danger' : "";})()}
                      />
                      { touched.rate && errors.rate && <p className="help is-danger">{errors.rate}</p> }
                    </div>
            </div>

            </React.Fragment>
            )
        }}
    />);
  }
1

1 Answers

3
votes

You can create a custom component and Pass the same to formik Field using component prop

For example

<Field name="name" label="Label" component={CustomInput} />

const CustomInputComponent = ({
  field, // { name, value, onChange, onBlur }
  form: { touched, errors }, ...props
}) => (
  <div>
    <Cleave
      placeholder="Enter your credit card number"
      options={{creditCard: true}}
      {...field} {...props} />
  </div>
);

For more refer to formik docs from link