我使用Fomik和Yup在应用程序中实现授权和注册。
我的计算机上有一个本地服务器。该服务器的文件夹位于我项目的文件夹附近。多亏了adonis serve命令,我才启动了服务器。服务器启动时。我在以下表单字段中输入:用户名,密码和其他...然后,如果验证成功,请按Submit按钮,然后从本地服务器收到响应。此响应包含jwt令牌。
现在,在验证表单期间,我只需检查用户名字段中是否写入了某些内容。但是我仍然需要验证用户名是否唯一,如果不是唯一的并且具有该名称的用户名已经注册,则在警报中显示错误。
在我的情况下,如何对用户名的唯一性进行验证并在警报中显示错误?
SignupForm.js的一部分:
const SignupForm = () => {
const history = useHistory();
const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({
initialValues: {
username: '',
password: '',
confirm_password: '',
first_name: '',
last_name: '',
phone:''
},
validateOnBlur: false,
validateOnchange: false,
validationSchema: yup.object().shape({
username: yup.string()
.required('This field is required'),
password: yup.string()
.required('This field is required')
.min(6, 'This password is too short')
.max(30, 'This passwors is too long'),
/.......
}),
onSubmit: async (formValues) => {
console.log('submit', formValues);
setSubmitting(true);
try {
const res = await api('api/auth/register', {
method:'POST',
body: JSON.stringify(formValues)
});
const token = res.token.token;
localStorage.setItem('myToken', token);
console.log('Result!',token);
history.push("/home");
} catch(e) {
console.error(e);
} finally {
setSubmitting(false);
}
},
});
return (
<form className="fform" onSubmit={handleSubmit}>
<SignupInput
label="username"
id="username"
inputProps={{
name:'username',
value: values.username,
onChange: handleChange,
onBlur: handleBlur,
disabled: isSubmitting,
}}
error={errors.username}
/.......
<button type="submit" disabled={isSubmitting}>Submit Form</button>
</form>
);
};
对于异步验证,可以使用formikvalidate
函数。
像这样:
...
validateOnchange: false,
validate: (values, props) => {
return fetch("https://reqres.in/api/users/2")
.then(res => res.json())
.then(res => {
const errors = {};
// if (res.data() === false) {
if (res.data.email === "[email protected]") {
errors.username = "user already exists !";
}
return errors;
});
},
validationSchema: yup.object().shape({
...
编辑
使用伪造的api的工作示例在这里:
https://codesandbox.io/s/jovial-galois-ndbcu?file=/src/components/Signup/SignupForm.js
另请参阅docs:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句