I'm using Formik and Yup. I can't figure out how I can specify a numeric field with no default?
Here are my validations:
const initialValues: any = {
string: "",
numeric1: undefined,
numeric2: ""
};
const validationSchema = yup.object().shape({
string: yup.string().required("Required"),
numeric1: yup.string().required("Required (numeric type)"),
numeric2: yup.number().required("Required (string type)")
});
Numeric1 is type=number and Numeric2 is type=text
If I specify a number type
<Form.Group className="mb-0" controlId="numeric1">
<Form.Label className="required">Number of users</Form.Label>
<Form.Control
type="number"
placeholder="Enter number (numeric type)"
{...getFieldProps("numeric1")}
isInvalid={touched.numeric1 && !!errors.numeric1}
isValid={touched.numeric1 && !errors.numeric1}
/>
<Form.Control.Feedback type="invalid">
{touched.numeric1 && errors.numeric1}
</Form.Control.Feedback>
</Form.Group>
I make the initial value Undefined, but then React complains that because the initial value can't be undefined A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen.
If I specify a text type
<Form.Group className="mb-0" controlId="numeric2">
<Form.Label className="required">Number of users</Form.Label>
<Form.Control
type="string"
placeholder="Enter number (string type)"
{...getFieldProps("numeric2")}
isInvalid={touched.numeric2 && !!errors.numeric2}
isValid={touched.numeric2 && !errors.numeric2}
/>
<Form.Control.Feedback type="invalid">
{touched.numeric2 && errors.numeric2}
</Form.Control.Feedback>
</Form.Group>
Then I get an unfriendly error message if I try to specify letters, because the Yup validation gets a NaN.
Code is here: https://codesandbox.io/s/numeric-validations-h50gg If you enter something like 'abc' in the numeric fields, you'll see what I mean (open the console log as well)
What is the best way to not have to specify a default for a numeric field?