No error messages after setting react formik validation

Viewed 1071

I am using react and formik.
I want to set a validation for a phone number.
I want to set up a validation for phone numbers so that if you enter anything other than numbers and hyphens, an error is displayed.
I created a validate function and added a phone number validation in it, but every time I enter a character, I get the following error and the error does not show the validation error.

error

36 Uncaught (in promise) TypeError: Cannot create property 'telephoneNumber' on string ''
import React from 'react';
import {Input, Form} from 'antd';
import {useParams} from 'react-router';
import {useFormik} from 'formik';
import {useCreateMutation} from 'api';

export default () => {
  const {userId} = useParams<{
    userId: string;
  }>();

  const [create, {loading}] = useCreateMutation({
    onCompleted: () => {
      resetForm();
    },
  });

  const validate = (values: any) => {
    const phoneValidation = /^[0-9-]+$/;
    const errors: any = '';
    if (values.telephoneNumber.match(phoneValidation) === null) {
      errors.telephoneNumber = 'phone error';
      console.log(errors);
    }
    return errors;
  };


  const formik = useFormik({
    enableReinitialize: true,
    initialValues: {
      email: null,
      telephoneNumber: null,
    },
    validate: validate,
    onSubmit: (values) => {
      create({
        variables: {
          uuid: userId,
          attributes: values,
        },
      });
    },
  });

  const {values, errors, handleChange, handleBlur, handleSubmit, resetForm} =
    formik;

  const validationPhone = /^0\d{1,4}-\d{1,4}-\d{3,4}$/;
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item label="e-mail">
        <Input
          name="email"
          value={values.email}
          onChange={handleChange}
          onBlur={handleBlur}
        />
      </Form.Item>

      <Form.Item label="phone">
        <Input
          name="telephoneNumber"
          value={values.telephoneNumber}
          onChange={handleChange}
          onBlur={handleBlur}
        />
         <div>{errors.telephoneNumber}</div>
      </Form.Item>
    </Form>
  );
};

1 Answers

As the error message said you can not create a property telephoneNumber on an empty string '', but you initialized errors as const errors: any = '';

Try to init the errors variable in validate function as described in the formik docs for validate as an empty object e.g. const errors = {};.

Here is a working stackblitz with some of your given code.

Additional example from the formik docs for validate function:

 // Synchronous validation
const validate = (values, props /* only available when using withFormik */) => {
  const errors = {};

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  //...

  return errors;
};

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

const validate = (values, props /* only available when using withFormik */) => {
  return sleep(2000).then(() => {
    const errors = {};
    if (['admin', 'null', 'god'].includes(values.username)) {
      errors.username = 'Nice try';
    }
    // ...
    return errors;
  });
};
Related