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 (
{errors.telephoneNumber}
);
};
