its*_*Jah 6 javascript node.js axios yup formik
我正在尝试验证注册表单上的电子邮件字段以检查它是否已经存在。为此,我正在检查在服务器上运行一个返回 true 和 false 的 GET 请求。
这是我对该字段的验证架构:
validationSchema={
yup.object().shape({
registrationEmail: yup.string().email('Invalid email').test('Unique Email','Email already in use', async (value) => {axios.get('http://localhost:5000/users/register', value).catch(err => console.log(err)) })
})
}
Run Code Online (Sandbox Code Playgroud)
问题似乎是值字段为空。如何将 Formik 字段中的值传递给我的函数?
编辑:管理使用以下发送值
registrationEmail: yup.string().email('Invalid email').test('Unique Email','Email already in use', function(value){return new Promise((resolve, reject) => {axios.get('http://localhost:5000/users/register', value)})})
Run Code Online (Sandbox Code Playgroud)
我仍然无法返回响应,这就是路由的样子
router.get('/register', (req, res) => {
User.findOne({email: req.body.email}).then(user => {
if(user){
return true
}else{
return false
}
})
})
Run Code Online (Sandbox Code Playgroud)
我解决了我的验证问题,我执行了以下操作:
registrationEmail: yup.string().email('Invalid email')
.test('Unique Email','Email already in use',
function(value){return new Promise((resolve, reject) => {
axios.post('http://localhost:5000/users/register/validEmail', {'email': value})
.then(res => {if(res.data.msg === 'Username already been taken'){resolve(false)} resolve(true)})
})}
)
Run Code Online (Sandbox Code Playgroud)
对于路线:
router.post('/register/validEmail', (req, res) => {
console.log('Request: ', req.body)
User.findOne({email: req.body.email}).then(user => {
if(user){
console.log({ msg:"Username already been taken" })
return res.json({ msg:"Username already been taken" })
}
console.log({ msg: "Username available." })
return res.json({ msg: "Username available." })
}).catch((err)=>{
console.error(err);
res.status(400).json('Error: ' + err)
})
})
Run Code Online (Sandbox Code Playgroud)
结果我必须使用 POST 请求,否则请求正文将为空。
我注意到您在问题中使用了 async/await,但您的答案使用了承诺。我更喜欢 async/await,最初认为 Yup 的测试功能不支持它,因为如果您的解决方案,但 Yup 确实支持 async/await!这是我的代码示例,供需要示例的任何人使用。文档中还有一些示例:https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
username: Yup.string()
.min(2, 'Too short, minimum 2 characters')
.max(50, 'Too long, maximum 50 characters')
.required('Required')
.test(
'username-backend-validation', // Name
'Username taken', // Msg
async (username) => {
// Res from backend will be flag at res.data.success, true for
// username good, false otherwise
const { data: { success } } = await axios.post(
"http://localhost:3001/api/users/register/validate-username",
{ username: username }
);
return success
}
)
Run Code Online (Sandbox Code Playgroud)