我正在使用在模式上定义的 Formik React Form 和 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 修剪空白而不显示消息?所以在提交表单时自动修剪空格?
有没有办法让 Yup 在不显示消息的情况下修剪空格
不是在一个单一的转换中。 formik 使用的 yup 转换仅用于验证。 您可以在传递数据之前创建一个单独的转换来使用,但它更简单,只需
valueToUse = userValue.trim()
自己。
你可以这样做:
onSubmit={(values) => {
const castValues = Contact.cast(values)
})
参考: https://github.com/jaredpalmer/formik/issues/473#issuecomment-499476056
通过重写
onChange
对象的 formik
方法,我能够实现自动删除电子邮件字段中的空格。这不是最好的解决方案,但它工作得很好,特别是在输入字段中的任何地方都不允许有空格的情况下。
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}
/>
...
)
您可以收听
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'),
});
您还可以随时随地修剪输入的文本,以完全限制用户在末尾使用空格(示例使用 React Native 组件):
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} />