typescript 使用Yup和Formik自动修剪白色

htzpubme  于 2023-03-31  发布在  TypeScript
关注(0)|答案(5)|浏览(121)

我正在使用一个Formik React Form和在schema上定义的Yup验证:

export const Contact = yup.object<IContact>().shape({
  contactName: yup
    .string()
    .trim('The contact name cannot include leading and trailing spaces')
    .strict(true)
    .min(1, 'The contact name needs to be at least 1 char')
    .max(512, 'The contact name cannot exceed 512 char')
    .required('The contact Name is required'),
});

有没有一种方法可以让Yup在不显示消息的情况下修剪白色?所以在提交表单时自动修剪空白?

nmpmafwu

nmpmafwu1#

有没有办法让Yup在不显示消息的情况下修剪白色
不是在一个单独的转换中。formik使用的yup转换只是为了验证。你可以在传递数据之前创建一个单独的转换,但是你自己只需要valueToUse = userValue.trim()就可以了。

0sgqnhkj

0sgqnhkj2#

您可以:

onSubmit={(values) => {
  const castValues = Contact.cast(values)
})

参考:https://github.com/jaredpalmer/formik/issues/473#issuecomment-499476056

cbjzeqam

cbjzeqam3#

我可以通过覆盖formik对象的onChange方法来实现自动删除电子邮件字段中白色。这不是最好的解决方案,但它工作得很好,特别是在输入字段中不允许空格的地方。

const { errors, touched, getFieldProps } = formik;

const { onChange } = getFieldProps('email');

const emailFieldProps = {
  ...getFieldProps('email'),
  onChange: (e) => {
    e.target.value = e.target.value.trim();
    onChange(e);
  },
};
  
return (
  ...
    <TextField
      {...emailFieldProps}
      error={Boolean(touched.email && errors.email)}
      helperText={touched.email && errors.email}
    />
  ...
)
nnsrf1az

nnsrf1az4#

你可以监听onBlur()事件。然后修剪字符串以实际修复任何尾随或前导空格:

onBlur={() => setFieldValue('email', values.)}

此外,对Yup进行修剪以进行确认:

export const Contact = yup.object<IContact>().shape({
  contactName: yup
    .string()
    .trim()
    .strict(true)
    .min(1, 'The contact name needs to be at least 1 char')
    .max(512, 'The contact name cannot exceed 512 char')
    .required('The contact Name is required'),
});
wmtdaxz3

wmtdaxz35#

您还可以在运行中修剪输入的文本,以完全限制用户在末尾使用空格(示例使用react原生组件):

const {handleSubmit, values, errors} =
    useFormik({
        validationSchema: EmailSchema(),
        initialValues: {email: ''},
        onSubmit: values => tryLogin(values.email)
    })

...

<TextInput
    value={values.email}
    onChangeText={text => handleChange('email')(text.trim())}
    error={errors.email}
/>

<Button title='SUBMIT' onPress={handleSubmit} />

相关问题