DEV Community

Discussion on: Schema Validation with Yup and Express.js

Collapse
 
jamesdev21 profile image
Semaj21

Hi. I am learning MERN stack. I have set up my express/mongodb as my backend. Now in my react client I am using react-form-hook with yup schema but how do I actually pass in the error response from express to validate on yup? I am validating for email uniqueness. Also, responses from express are not logging to console when I implemented the yup schema. I dont get the status 400, email is already used, anymore. Any help would be appreciated. thanks

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.