KelvinLB
KelvinLB

Reputation: 13

how to validate "input type = 'date' " with Formik and Yup

I am starting in React and now I have the challenge of form validation and for this, looking for ways to work with the validations I found the Formik and Yup libraries But it turns out that there is no example of how to validate an "input type = 'date'", I only see examples where they use "DatePicker", to which I ask if there is any way to be able to solve this using "input type = 'date' Then I will show you how I am trying to validate this date.

    const validationSchema = Yup.object().shape({
      name: Yup.string()
      .min(2,"El nombre debe contener mas de 2 caracteres")
      .max(60,"El nombre no debe exceder de los 60 caracteres")
      .required("*El nombre es requerido"),
      inicio: Yup.date()
      .min(Yup.ref('originalEndDate'),
      ({ min }) => `Date needs to be before ${formatDate(min)}!!`,)
    });
    function formatDate(date) {
      return new Date(date).toLocaleDateString()
     }

 <Formik initialValues={{ name:"",inicio:""}} validationSchema={validationSchema}>
                {( {values,
                    errors,
                    touched,
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting }) => (
                        <Form.Group>
                            <Form.Row>
                                <Form.Label column="sm" lg={1}>
                                        Creada Por:
                                </Form.Label>
                            </Form.Row>
                            <Form.Row className="col-form-label">
                                <Form.Label column="sm" lg={1}>
                                Nombre:
                                </Form.Label>
                                <Col>
                                    <div class="col-10">
                                        <Form.Control type="text" defaultValue={values.name} name="name" placeholder="Nombre de campaña"
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            className={touched.name && errors.name ? "error":null}/>
                                        {/* Applies the proper error message from validateSchema when the user has clicked the element and there is an error, also applies the .error-message CSS class for styling */}
                                        {touched.name && errors.name ? (
                                                <div className="error-message">{errors.name}</div>
                                            ): null
                                        }
                                    </div>
                                </Col> 
                            </Form.Row>
                            <Form.Row>
                                <Form.Label column="sm" lg={1}>
                                Inicio:
                                </Form.Label>
                                <Col>
                                    <div className="col-10">
                                        <Form.Control type="date" placeholder="" defaultValue={values.inicio}
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        className={touched.inicio && errors.inicio ? "error":null}
                                            />
                                    </div>
                                </Col>
                                <Form.Label column="sm" lg={1}>
                                Fin:
                                </Form.Label>
                                <Col>
                                    <div className="col-10">
                                        <Form.Control type="date" placeholder="2011-08-19"
                                                />
                                    </div>
                                </Col>
                            </Form.Row>
                            <h5>Indique el objetivo a cumplir para esta campaña</h5>
                            <Container>
                                <Form.Check required label="Incrementar volumen de ventas"/>
                                <Form.Check required label="Incrementar repetición de venta"/>
                                <Form.Check required label="Mejorar lealtad"/>
                                <Form.Check required label="Crear awearness"/>
                                <Form.Check required label="Acción correctiva"/>
                            </Container>
                            <Container>
                                <Button as="input" type="button" value="regresar" />{' '}
                                <Button as="input" variant="primary" type="submit" value="Crear campaña"/>
                            </Container>
                        </Form.Group>
                    )}
                </Formik>

I am looking for a solution for this if it exists

Upvotes: 1

Views: 8521

Answers (1)

Gerardo Perrucci
Gerardo Perrucci

Reputation: 734

Using transforms:

import { date, object } from "yup";

const today = new Date();

const schema = object({
  birthday: date().transform(parseDateString).max(today),
});

const isValid = schema.validateSync({
  birthday: "2020-02-02",
});

Ref: https://codedaily.io/tutorials/175/Yup-Date-Validation-with-Custom-Transform

Yup: https://github.com/jquense/yup#mixedtransformcurrentvalue-any-originalvalue-any--any-schema

Upvotes: 3

Related Questions