【发布时间】:2021-09-06 11:41:38
【问题描述】:
我正在做一个使用 Native-Base 样式库的 Expo/React-Native 项目。为了验证表单,我使用 Formik + Yup。
所以我有这个登录屏幕,并且“onSubmit”方法仅在验证工作时被调用,但是当验证失败时,即使我选择使用
这是我登录屏幕的相关部分
export default function LoginScreen(props) {
const { handleChange, handleSubmit, handleBlur, values, errors } = useFormik({
initialValues: { username: "", password: "" },
validationSchema: LoginSchema,
onSubmit: (values) => {
console.log(values);
},
});
return (
<SafeAreaView>
<Center width="90%">
<FormControl marginTop={10} marginBottom={5}>
<FormControl.Label>Email ou nome de usuário</FormControl.Label>
<Input
type="text"
onChangeText={handleChange("username")}
onBlur={handleBlur("username")}
value={values.username}
/>
<FormControl.ErrorMessage>{errors.username}</FormControl.ErrorMessage>
</FormControl>
<FormControl>
<FormControl.Label>Senha</FormControl.Label>
<Input
type="password"
onBlur={handleBlur("password")}
onChangeText={handleChange("password")}
secureTextEntry={true}
value={values.password}
/>
<FormControl.ErrorMessage>{errors.password}</FormControl.ErrorMessage>
</FormControl>
<Button marginTop={5} onPress={handleSubmit}>
Login
</Button>
</Center>
</SafeAreaView>
);
}
这里是 Yup 验证模式
export const LoginSchema = Yup.object().shape({
username: Yup.string().required("Este campo é obrigatório"),
password: Yup.string()
.max(20, "Senha muito longa")
.required("Este campo é obrigatório"),
});
【问题讨论】:
标签: react-native formik native-base yup