如何使用 Formik 和 Yup 验证"input type = 'date' "



我从React开始,现在我面临着表单验证的挑战,为此,我找到了Formik和Yup库,寻找使用验证的方法但事实证明,没有关于如何验证";输入类型="日期";,我只看到他们使用";DatePicker";,对此,我询问是否有任何方法能够使用";输入类型="日期"然后我将向您展示我是如何验证这个日期的。

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>

我正在寻找一个解决方案,如果它存在

使用转换:

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",
});

参考编号:https://codedaily.io/tutorials/175/Yup-Date-Validation-with-Custom-Transform

是的:https://github.com/jquense/yup#mixedtransformcurrentvalue-任意原始值任意-任意模式

最新更新