我正在尝试以 formik 形式创建一个具有 max-limit(250 个字符)属性的文本字段。我想在用户尝试输入第 251 个字符时显示内联验证错误。我正在使用 Yup 进行验证。 问题是,使用 maxlength 属性,它永远不会让我写入第 251 个字符来触发错误。
inputProps={{
maxLength: 250,
}}
我的 Yup 模式看起来像这样:
const descriptionValidation = Yup.string()
.max(250, 'Description cannot exceed 250 characters')
.optional();
我尝试将 251 作为最大限制,并在输入最后一个字符时触发字段触摸,但它有两个问题:
<Field
as={TextField}
name="description"
label="Description"
multiline
rows={4}
placeholder="Optional"
InputLabelProps={{
shrink: true,
}}
inputProps={{
maxLength: 251,
}}
error={Boolean(errors.description && touched.description)}
helperText={errors.description && touched.description && errors.description}
onChange={(event: SelectChangeEvent) => {
const { value } = event.target;
setFieldValue('description', value);
if (value.length > 250) {
setFieldTouched('description', true);
// setFieldValue('description', value.slice(0, 250));
}
}}
/>
那么有什么方法可以实现这个目标吗?
由于您使用
yup
验证表单,因此不再需要 inputProps.maxLength
。
它需要比所需的额外字符(我们可以在提交时删除该字符,但我认为这太麻烦了)
如果您从
values
获得表格 Formik.onSubmit()
,您可以放心,所有字段都是有效的。如果验证表单时出现任何错误,Formik.onSubmit()
将不会被调用(表单未提交)。
是的,只有当我从现场集中注意力时才会触发验证
情况并非如此。默认情况下,每次字段值更改时,
formik
都会验证。您的代码不起作用,因为 touched
在字段模糊之前不会获得更新。
在下面的代码中,我删除了
inputProps.maxLength
和 touched
的使用。一旦描述超过 250 个字符,就会显示错误。
import React from 'react';
import { Form, Formik, Field } from 'formik';
import { Button, TextField } from '@mui/material';
import * as Yup from 'yup';
const FormSchema = Yup.object().shape({
description: Yup.string()
.max(250, 'Description cannot exceed 250 characters')
.optional(),
});
export default function MyForm() {
return (
<Formik
initialValues={{
description: '',
}}
validationSchema={FormSchema}
onSubmit={values => {
console.log(values);
}}
>
{({ errors }) => (
<Form>
<Field
as={TextField}
name='description'
label='Description'
multiline
rows={4}
placeholder='Optional'
InputLabelProps={{
shrink: true,
}}
error={Boolean(errors.description)}
helperText={errors.description}
/>
<Button variant='contained' type='submit'>Submit</Button>
</Form>
)}
</Formik>
);
};
参考: