express-validator Node.js tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
now what is going on guys today we're going to take a look at this little library here called express validator which allows you to validate the incoming payload to your server so to check if specific fields are present so they are not null whether fields fulfill specific conditions like a string has a particular length yeah so i would say let's just try out this library right so let's go to the terminal let's make a new directory and let's call it express validator tutorial and let's cd inside of this directory and i'm going to say npm init yes to create a package.json file and i'm going to install express and i'm also going to install this express validator thing so i'm just going to copy this and i'm going to paste it over here cool so now we have a package.json and then it will install like these two packages cool so now it's done installing let's open this thing up in our favorite code editor and one more thing i would like to do this time around i want to use typescript simply because a lot of people ask me for doing a little bit more with typescript so i'm going to say npm install save dev type script i also need the express.js types and what i also need is something called ts node dev and this package actually is the typescript equivalent for a node mod so it allows you to do hot reload and it's like pretty handy so i would recommend it it's pretty nice so yeah now we have it and the first thing is maybe let's directly create an index.typescript file cool so now we should have everything we have an index.typescript file we have a package.json file with all the types we need and the first thing i want to do is oh actually we forgot one thing we need to create a ts config file and the way you can do that is with npx tsc so typescript config and then dash dash init it's important to have dashed or to do dash dash in it so just tsc in it will not work you need to do dash dash in it cool so now we have a typescript a ts config file and now we are actually good to go okay and the last step in the setup would be to activate this hot reload feature so if you go to this repository and you scroll down you can see okay here i only have to run this command which is like some alias it's t is no dev and then a couple of options so i'm just going to copy this i'm going to head over to the package.json file i'm going to say def and i'm going to paste it in here and instead of saying server.ts i'm going to say index.ts okay so i think now we're done with the typescript uh setup of this and to try out this package we obviously need an express server and to speed things up a little bit i'm just going to go to this documentation here so if you go to the repo and you click documentation then you end up on this page and here you can see they offer like different examples and i'm just going to take the typescript example and i'm just going to copy paste it and then we're going to modify it a little bit so it's a little bit more scalable okay and we need to import the proper types so i want to import this request and the response so i'm going to say request response from express and we also need to create like an application and one thing that is important so if you try to do this it won't work so you cannot destructure and then have the default export the default export needs to be on the left x press so that will work actually cool so i'm going to do const app equals express and i'm going to have it like that and let's get rid of this it's a little bit shorter and we don't care about that the only other thing that's left is we need to run this so i'm going to say app.listen i'm just going to run it on port 8080 make sure to have a console lock running on port 8080 so you know whether everything is working properly cool so that itself should work so let's try to dig into this a little bit so first of all i'm going to make this slash register simply because the example what we're going to do here is we're going to pretend that we sign someone up like we register a user and there you need to pass a username and a password cool so what you can see here is you have the path like or first of all the http verb and then the path and then you can specify like a couple of constraints you want to enforce so you can say in the body i want this username field which i'm going to rename to email i want to apply the following constraint and then you have this is email so under the hood this is just applying some regular expression to check if the string that you have passed is an email and then you can say okay in addition i have like a field called password and this password field needs to have a minimum length of five okay and then you have the normal request response next handler so we don't have next here because we don't need it and this part here is actually important so in here what it says is it looks at this request object and see and because we have specified these constraints before uh our like library or this express validator and we'll just take the payload and like check whether these constraints here are true or whether they're fulfilled and if they're not fulfilled then you will get back like uh an errors so you check whether the errors are empty and if it's not empty you return a bad request so this is like the minimal example of all of this and what i want to do now is i want to try this out so let's make this really practical so i'm going to say npm run oops npm run def cool so hopefully our server is starting up yes and i already prepared like a postman so what i did is i have like post towards register on localhost port 8080 i pick the raw option and then i pick json and i just want to show you something interesting so let's do it properly let's take like a correct email testattest.com and a password that fulfills all the all the criteria so at least five characters long and i think i forgot one thing i need we need to send status to one right because we actually need to reply because we deleted this user creation over here okay so now this is like modified and let's try to run this bam oops that's kind of weird so it's a little bit confusing right because this is a real email and this is a proper password so why is it now returning like errors all over the place is this library actually working yes of course it works but there's one one little detail that you need to take into account you need to plug in a json parsing middleware so in case you ever wondered why you need this well the request is coming in and it's basically just text or like a string and what we need to do is we need to take this string and we need to convert it to a javascript object because this right our software like it only works with javascript objects so we don't want to work with plain strings so now the payload or this request.body is actually a javascript object and let's try to run this and let's try oh let's check out whether it works now bam okay fair enough now it's created i just wanted to show you like this upfront because the first time you're going to do it maybe you forget it and then you run into this one more thing i want to show what happens if this is null yeah then you see okay you get an invalid value that is okay so you get back this errors array but what happens if this is null here do i also get an error yes you do so this uh library here like it also checks like if you say dot is email then it also checks whether it's not just wanted to mention that here another thing or another caveat i wanted to show is now what happens if i have an additional field and i just say uh first name so let's assume i have like a first name and that's it like i don't have any additional constraints on this one the only constraint is that it needs to exist right yeah so there is like an additional method here which is called exists and this method allows you to enforce that a particular field is required i just wanted to mention that here because you're probably going to need it very often and let's put it like this and let's try it out okay so i have this over here bam oops and you already see okay nice you have like uh an error message but what happens if i do something like this pass like an empty string what happens then oh i forgot to add a comma here here the top this one oops so you see that one is a little bit strange because exists actually only checks whether it's undefined or not so that means if you don't include it in the payload it's going to complain if you pass an empty string well okay yeah maybe it allows it that could be expected but what happens if it's not yeah so you see this exists only checks if it's undefined or not i just want to point that out up front because it's very it's easy to forget and there's one additional option you can pass in this exists thing so that it also checks for faulty values and you can see that in the documentation so you can see here check null if you say check null then it will also return an error if it's not and if you say check falsey then it will also check if it's empty string zero false or not so in that case um you could say something like uh check uh you need to pass an options object and you need to check check falsey true okay so now all these edge cases here if it's like an empty string you will also get an error back which is good i just wanted to point that out up front because having like a required field is one of the most common things that you want to do in your request body validation but actually we don't need this one for example okay one more thing i wanted to point out here is that this code here it's quite repetitive right say i have another route or 10 other routes then every time i would need to explicitly check for these errors so it's like not the best setup right so let's cancel this and let's put this inside of its own middleware so let's make a directory let's call it middleware and inside of this middleware directory i'm just going to give it like some name so i will say validate request schema dot ts make sure to have the proper extension so you can say export function validate request schema and then request response next and in here we actually need the next function you're soon going to see why so this one and this one and this is actually the next function so by the way this these things yeah they are the types for express response okay and i'm just going to take this and i'm going to cut it and i'm going to move it to over here yeah and the only thing we still need is we need this validation result so let's take this copy it as well paste it in here let's get rid of that and one more thing now we check for the errors but if there's no error we actually want to proceed so that's why it is imperative that you call this function here i mean if you don't you will quickly notice that it doesn't work okay so here we check for the errors if it's an error we return a bad request now by the way this is also not ideal so ideally you have like some error handling middleware and then you can throw a throw in here so throw a new custom error or i don't know throw new bad request error then you can pass details and your error handling middleware would take care of it or another option is if you have something like this and you define a static class and you say api error.bad request although i do have to say i like the first approach better because it's scales more like for production application it's easier to maintain yeah but i'm not going to do that in here because the like the purpose of this tutorial is not to show you like the perfect way on how to do error handling okay so this is like our uh like middleware and the important thing now is that you only plug in this middleware after you have specified the rules obviously so if you were to plug in like your middleware like this it would not work right because it wouldn't know like what to validate there's zero rules so it's going to succeed so that's why it's important that you put this validate request schema here after the rules okay this is really important and make sure to not call it so don't do something like this yeah you see in typescript already shown you an error but it actually has to be a middleware so a function with request response next cool so that looks pretty good uh one more thing i wanted to show you so this here is okay like if it's only two fields it's fine um maybe in the future though you might want well if you want to reuse some of the schema you might want to say ah you know actually it would be good if we had like an or like our own directory where we can specify like the schema or the dto or however you want to call it and what i'm going to do is i'm just going to do that here so i'm going to call this register schema and we're just going to outsource this so i'm going to take that copy it and then i'm going i will go inside of this directory and now things are going to get interesting so we can say cons schema equals and the interesting part here is that we can return an array right because how else would you return these these things right you you need to return one value you can't return multiple and returning it as an array is totally fine so you can also do something like this like make this an array oops like this this also works i just wanted to point that out good so i'm going to take this make it an array and now i need to import like this import body from express validator cool and now what you what we have done is we've put this schema inside of a inside of its own file uh it might make sense though if it gets bigger to kind of co-locate this because now we have it in like one dedicated folder and if we have 100 endpoints it's going to get pretty messy to figure out like which schema where or what schema we're actually going to use but yeah i think for this tutorial it's fine just wanted to point that out maybe you want to co-locate this so you move this to like a routes directory and then you co-locate you have a dedicated folder maybe for each request and then you can do it like that but i'm just going to leave it like this i just want to show you that in principle you could schema as register schema i just wanted to show you that in principle you can and put this inside of a dedicated file and now instead of doing it like this you can just do it like this and i think that's much better isn't it so we just need to input this import bridge register schema from schema register schema i mean that looks much cleaner right you don't have like this you don't have everything crammed inside of one file you now have it properly yeah now talking about cramming everything in one file let's also do it properly and let's move like the routes to its dedicated folder now this is not really required for understanding this express validator library but it is like the better approach in my opinion so let's clear this up make another directory call it routes and here it is and i'm going to say index.ts and then inside of here what i want to do is i want to import a router from express and then i say const root router equals router and then i take this and i cut it right because after all you don't want to cram everything inside of your index.js file that's just very ugly and i can actually just copy like all the imports and then router okay and here we need to change the path okay and then we can say export i don't know root router as router okay yeah so that is good i think well that's better than before right you don't have everything in one file and the only thing we now need to do is we say app.use router so this is much better it's much cleaner like i would always recommend to index ah no actually you don't need that okay cool so this should work and uh yeah let's try this out and let's see how it goes npm run dev and i just want to show you like a few caveats regarding this okay so now we have this you already saw like if we make a request oh let's put a let's remove this remember we remove the first name you can see that it always returns this invalid value can i zoom in in this thing oh it's kind of hard to zoom in here okay but you can see like it always returns this invalid value and that's not the best it's not the best thing right because invalid value what does that mean and you can add custom error messages so you can say something like with message and you can say email must contain must be must contain a valid email address okay and then you can say with message password must be at least five characters long now yeah so that is pretty good i would say let's get rid of this yeah that's good and let's try this out so i'm going to run this yeah and now you can see at least we have like the correct error messages and if i pass like an invalid email address you can see okay you get back the errors array and you can also see okay it returns you the original value and it can it returns you a proper error message now in certain cases you might even localize this error message depending on the location so depending on the language i don't know if the customer is sitting in spain like you return a spanish error message but that's i18n internationalization it's a different topic again cool so yeah that's it pretty much um i think or hopefully you now have an idea like how to use this library i think the setup makes sense have like your own middleware to to check whether you have any errors and maybe even outsource it to like own file as i said maybe this schema folder it should go like somewhere else but that's like a different discussion cool so uh thank you so much for watching leave a like and subscribe to the channel if you have a question just leave me a comment below i'll try to answer like all of them and yeah thank you so much and if you have another question and you want to reach out on a different channel you can also reach out on twitter my twitter handle is at productioncoder so yeah that's it pretty much and uh subscribe to the channel and i'll see you in the next video bye
Info
Channel: Jan Goebel
Views: 34,606
Rating: undefined out of 5
Keywords: express validator, express validator node js, express validator tutorial, express js validation, express validator middleware, express validation middleware, node js validation middleware, express body validation, expressjs validator, node js express validator, express validator node js hindi, express bad request, express validator typescript, typescript request body validation, how to use express-validator in node js, express validation
Id: 7i7xmwowwCY
Channel Id: undefined
Length: 23min 36sec (1416 seconds)
Published: Mon Mar 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.