'TextField for allowing users to add an amount of time in decimal and time format

I am trying to implement a TextField that allows users to specify the amount of time it will take to complete a project.

I want them to be allowed to add the time in both formats:

  1. 1.5
  2. 1:30

I am having struggle because of my Formik and Yup integration. I am using Material UI but MUI's time pickers only allow the time format.

My validation schema:

const RegisterSchema = Yup.object().shape({
  estimatedhours: Yup.number().positive('Must be positive').max(99999)
});

My formik integration:

const formik = useFormik({
  initialValues: {
  estimatedhours: data?.proj_estimated_hr || '',
  },
  validationSchema: RegisterSchema,
  onSubmit: async (values, { setErrors, setSubmitting }) => {
    try {
      // the rest of the code
    } catch (error) {
      console.error(error);
      if (isMountedRef.current) {
        setErrors({ afterSubmit: error.message });
        setSubmitting(false);
      }
    }
  }
});

My textfield:

<TextField
  fullWidth
  label="Estimated hours"
  type="number"
  value={formik.values.estimatedhours}
  disabled={isSubmitting}
  {...getFieldProps('estimatedhours')}
  error={Boolean(touched.estimatedhours && errors.estimatedhours)}
  helperText={touched.estimatedhours && errors.estimatedhours}
  onInput={(e) => {
    e.target.value = Math.max(0, parseInt(e.target.value, 10)).toString().slice(0, 5);
  }}
/>

I don't want to allow the user to also be able to type 1.5 if they already typed 1:30 and vice versa.

I would love a pre-built library to handle this or if anyone has already made a custom solution for this. I am not that good at development and if someone already has put something on npm, they don't explain it very well how their solution works.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source