DEV Community

Discussion on: Schema Validation with Yup and Express.js

Collapse
 
franciscomendes10866 profile image
Francisco Mendes

In the frontend you should only validate the input data, checking if they follow the rules specified by yourself and just that.

In the backend is another layer of "security" to verify that each of the data is correct. Now if you are validating if the email is unique this is not done by yup but by the ODM/ORM you use and the error has to be handled by you.

Something like this:

const exists = await Users.findOne({ email })
if (exists) {
     return res.json({message: "Email already taken."})
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jamesdev21 profile image
Semaj21 • Edited

Yes, I have two validations. From backend and frontend. backend is fine. It checks, validate and send a response. My backend sends an error response with "400, Email is already exists" if an email is already exists from mongodb. I tested this on Postman as well. Now my problem is how do I pass this response to react-form-hook with yup schema? that's where I'm stuck. The axios request is on react-form-hook onSubmit. Thanks btw

Thread Thread
 
franciscomendes10866 profile image
Francisco Mendes • Edited

Ah ok I get it, I would use .then() with axios. And then it would have two states with the useState() hook. Something like this.

axios.post('/').then((res) => {
   if (res.message) {
     setIsError(true)
     setErrorMessage(res.message)
   }
})
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jamesdev21 profile image
Semaj21

Alright, thanks. I'll try it out.