我从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>
我正在寻找解决方案,如果存在的话
答案 0 :(得分:0)
使用变换:
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-any-originalvalue-any--any-schema