React Form Validations ( with YUP ) - Full Tutorial 2024 πŸ”₯πŸ”₯

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so let's say we have a form that looks something like this this has first name last name email phone number password this more like a sign up form right so one thing that is very important in such forms or any form for that matter is validation now what do I mean by that so let's say inside of this email field I type P now this is not an email right so if I just go on and submit it you're going to see just ignore all the others but this shows that invalid email format and now if I go on and try to do p at gmail.com and if I go and try to submit it again you're going to see this email error is now gone so this is basically what a form validation is all about and in this video we're going to see how we can Implement custom validations on our own and also an amazing Library called yep which makes adding form validations 10 times easier so let's go on and jump to our vs code and over here I'm going to open the terminal and I'm going to initialize a new react tab so I'm going to say npm create wheat at latest and I'm going to press press enter so it's going to ask us the name of the folder I'm going to press dot because I've already opened a folder called react yep so it's going to create it inside of this directory itself now it's going to ask us a framework so I'm going to choose react and I'm going to choose JavaScript cool so our react app has been initialized successfully Let's uh install all of the dependencies by typing npm install and what basically this is going to do is it's going to install all of the dependencies inside of this package.json file like react react doome and other dependencies okay there we go now I'm going to go inside of our SRC folder and remove the things that we don't need like this assets folder and S of index CSS I'm going to remove all the Styles instead of app. CSS I'm going to remove all the Styles and just add a body style of font family sanserif and inside of app.js or app.jsx I'm going to remove this state all of these files over here and simply I'll add one div which will say subscribe to roadside coder which you should if you haven't yet so let's save this and now if I try to run this npm run Dev let's click on this link and we can see our react app is successfully running now let's try to recreate that form UI that we saw at the starting of this video so I'm going to Simply create a new folder over here for components inste of it I'm going to create a file which I'll say form without yep so in this file or in this component I'm going to implement the form validation without using any Library without using yep so that even if you had to implement custom validations in your company you can do that as well so I'll say r a fc press enter so I'll just name the component as form without yep I'm going to remove this import and if you don't know how I did that rafc I have this extension over here called es7 react Redux react native Snippets so you can install that and you can use this shortcut as well so okay let's copy this up and render it inside of app.jsx inste of this Dev I'm going to say form without yep import it and cool let's see yep we can see that hello cool now inside of this component I'm going to get rid of this div and instead I'm going to have a form tag which will have an on submit on submit it will call a function called handle submit so this function doesn't exist yet so let me just create it right over here const handle submit equals an empty function for now now inside of this form I'm going to create a few Fields like first name last name let's let's just have a look so first name last name email phone number password and all these things so let's just create a state for storing all of the values of these inputs right so I'll just import use State hook over here which allows us to manage the state of our app and it returns us with an array with two things one is a variable which I'm going to call form data and other is a set form data or a set function which helps us to manipulate the data ins out of this form data now let's give it some initial value as well so I'm going to take an empty object over here and all the fields that we just saw I'm going to provide some initial data with respect to that which is going to be this so let me just close this yeah first name last name all of these will be empty by default email phone number password confirm password age gender interests interests will be an array because there can be more than one interest and the birth date okay now inside of our form let's create all of these input Fields one by one so first of all we're going to have for our first name so label is going to be first name and then we're going to have an input field of type text name I'm going to give to first name value I'm going to take form data. first name which we have taken from over here so form data. first name initial value and some placeholder of enter your first name so let's have a look yep there we go we can see the first name over here let's do the same for other input Fields so I'm going to add for last name same a label and an input field also so let me just wrap each of these inside of our Dev this one as well okay below this I'm going to have for our email so for email label is going to be email input type is going to be email or you can keep a text as well because anyways we're going to add the validation later on name is going to be email value form data. email again taking from over here and a placeholder enter your email next I'm going to have for our phone number so label is going to be phone number input type is going to be text name phone number same as first name and last name after that I'm going to have password and confirm password so simply password is going to be of type password so whenever we type inside of this input field we can see this oops oh okay we can't we cannot type it right now because obviously we haven't added the on change over here so if I just show you if I give it some default value and if I go back over here yep you can see we can see these black dots so okay password similar to previous ones just the type password same with the confirm password as well and we will add a validation into our confirm password that this should be same as the uh our entered password that you may have seen in other websites as well right below this I'm going to have age field label will be age input will be type of number this is very important because age is always going to be number right it can't be a letter name is going to be age value form data age and some placeholder below this let's add some checkboxes no not check boxes I think I'm going to have gender over here so for gender let's add a select so simply I'm going to have a select tag called gender value is going to be form data. gender inside of it I'm going to have some values right so if I go on over here you're going to see this is more of a drop down I think I can remove this select gender from over here I think it's self-explanatory from that yep you can see we can select our gender from over here then below this let's add check boxes for our interest so it's bit long yeah so label interests and inside of it I'm going to have three input boxes of type checkbox if it's checked or not I'm going to see from our form data. interest so this is an array right so I'm going to see does this array includes this current coding checkbox or not so we have coding uh we have sports we have reading so similar to each other and the last input field I'm going to keep is date of birth so the reason I'm keeping all of these input Fields over here so many input Fields because these are the all possible things that you can encounter in a company right a lot of videos that you will see on YouTube they will just show you email password and they'll just get done with it so I don't want that I want to show you all of these input Fields that's why I'm including this long form so for date of birth label will be date of birth input type is going to be date name is going to be birth date some value from our form data and the placeholder and I think that's pretty much it I'm not going to add anything else inside of it just one button at the very end for submitting our form so button is going to be type submit it's going to be called submit cool this looks good now let's just add some bare minimum styles to it so that uh we have some gap between these input Fields so instead of app. CSS I'm going to close yeah app. CSS I'm going to have a form tag or let's just give this uh a proper class name so for form I'm going to give class name of form and I'm going to say do form instead of it I'm going to have display Flex and flex direction to be column and we're going to include some gap between each of these so let's say 10 pixels of Gap so if I see yep we can see some Gap over here and for our form inside of it I'm going to go to label and so these are the labels so I'll just add some gap between label and the input so I'll just say margin right to be 10 pixels cool now first thing first how do we change all of these input Fields because right now we can't type it over here right right so I'm going to just create a simple handle change function over here const handle change and this will take an event now this uh handle change will proved to all of these fields like U for example in our input field I'm going to say on change it's going to be handle change and ins start this handle change it's going to receive an event and from the e. Target or the event. target I'm going to receive two things first the name and the value so name will be the uh this thing first name which is similar to what we have added inside of our state as well so we're going to know that okay we're supposed to change this first name and the value which is coming from our onchange function so simply I'll just say set form data and I'm going to add an object I'll take whatever's already inside of it so form data comma and for that particular field so I'll say name and I've added these Square braces over here because you can't just directly write name and value over here if you want this name to be a key you have to keep it inside of a square bracket so cool let's just try to go and change this p i Yu s okay yeah we we're able to do that not able to do that for last name because we haven't added it inside of that so I'll just take this on change and add it for each of these for email as well phone number password confirm password age for gender I'm going to add it insert this select for this thing for checkbox it's going to be different um but for our date it's going to be the same so for checkbox I'm going to create a separate thing I'll just create a handle change or handle checkbox change yeah just add this here over here and in our third checkbox and let's just go ahead and create this function right here right below handle change so cons handle checkbox change this will be kind of similar to this handle change but one difference so instead of this name and value I'm going to take name and and checked over here to just to check if the particular check box we are clicking on is checked or not now let's create a variable over here called updated interests interests equals I'm going to take all of the interests inside of our form data so interests so I'm just creating a backup over here so that we can make the changes to this and then push it back inside of that state so now I'll say if the current checkbox is checked if it's checked then I'll say updated interests dop push this name over here I'm going to push that particular checkbox else I'll say updated interests equals updated interests dot filter that is we're going to remove it from over here right so I'll say interest and I'll say interests not equals to name yep and yeah this is giving us err because this is Con this should be let if you want to override it and yeah I think that's uh pretty much it let's just say set form data let's take whatever is inside of our form data data oops form data and just add interests to be updated interests now in this case we haven't added uh the square bracket over here because we want the name of the key to be interests which it's already is right over here okay I think uh this should be good enough let's try changing all of these fields okay we're able to enter some email over here some password Okay Age cool yep we're able to change the gender as well cool this works everything works awesome if you press on submit it's going to I guess refresh the page yeah let's take care of that inside of the handle submit I'm going to say take e and I'll say e do prevent default for preventing the default Behavior okay now inside of it I'm going to check for our validations so I'll create a function over here const validate form now this validate form is going to be the one that is going to validate and give us errors so I'm going to take this validate form and call it right over here and this will return as const is valid key and I'm going to check if this is valid if the form is valid then I'm going to Simply console log form submitted and I'll just display form data else I'll say console.log form validation failed okay now let's go on and create this validate form function over here but before that if you're preparing for your front end interview and you would like me to help you in your frontend interview preparation just click the link in the description down below and book a one-on-one call with me we're going to discuss tips tricks I'm going to give you a lot of resources I'm going to design a proper road map tailor to your situation which is going to help you out a lot in your front-end interview preparation so click the link in the description down below and book a one-on-one call with me so I'm going to create a state over here for storing all of our errors inside of it so const errors and set errors now I'm warning you this function over here is going to be so so long because implementing custom validations is literally a headache and it just involves so much redundant code as well so let me show you if I just uh you know copy this function that I've already written over here you'll see so if I start from the beginning I have this new errors object I've already initialized over here so first of all I'm checking if form data. first name doesn't exist then inside of the new errors object I'm just going to add this first name key and just add first name is required same with last name as well same with form data. email if it doesn't exist give the error that email is required else if it is existing I'm going to check if the email is valid or not so if email is not valid then I'm going to say invalid email format and this is valid email is not created yet so let me show you what type of function this will be it will look something like this is valid email and over here I'm adding this Rex expression which you don't need to understand reject is something that everyone copies from the Google even if it's a senior developer or a junior developer and simply I'm just testing is the format of the email similar to the email reject over here if that's the case then it's a valid email else I'm going to say invalid email format same with our phone number as well I'm going to check if the number of digits inside of a phone number is 10 else I'm going to give the error phone number must be 10 digits so this is how a function will look like is valid phone number and I'm adding a Rex over here which is just checking for 10 digigit phone number and it's going to return false if it's not 10 digigit same for our valid password as well first of all it will check if password is present or not else it's going to check password must be at least eight characters long at least one symbol one number one lowercase letter right so let's add uh this is valid password function and the reason why I'm moving fast over here is because I want to show you how easy these things are to do in yep by using you know a library like yep so let me just show you this first so yeah you see is valid password it's going to check first of all it it should have any of these symbols it should have a one at least one number at least one capital letter and a small letter and then over here simply I'm going to check if the password's length is more than or equals to 8 and all of these criterias over here so you see it's such a headache for checking all these validation same for our confirm password same for our age as well for age simply I'm going to have a function which is going to look like this inside of it I'm going to check if age is more than or equals to 18 and age is less than or equals to 100 and you can see we are parsing this over here by converting you know age from if it's a string to uh number and this is something which is also a part of yep and it comes inbuilt inside of yep and I'll show you that as well as this Mo video moves forward so yep is valid age if not if it's not valid then I'm going to show you you must be at least 18 years old old and not older than 100 years and same uh similar validations for our gender for our interests interest has to be more than zero if it's zero then at least one interest you should be having same with our date of birth as well and in the end I'm going to assign this new errors to our set errors function and now simply in the end I'm going to check object. Keys new error it's just checking that if there is at least one error present then it's going to return false so right over here and now if I go back and I'll show you if I go to inspect and open the console let me just um console log errors over here so I haven't typed anything inside of this form if I just press submit over here you're going to see we get this object with all of these errors inside of it age is required birth date is required blah blah blah blah so let's see if I add age over here let's say 25 and if I submit this you going see there is no age error over here so let's just render all of these errors inside of our UI to see it better so below each and every input field I'm just going to Simply add if errors do first name is there then render that error do first name and it's going to have a class name of errors and I'm going to Simply do this similarly to all of others as well like over here for our last name last name for our email for our phone number our password sorry this will be over here inste of our password this will be over here for our confirm password and if I go up and show you I've added this condition over here as well that if confirm password is not equal to the password password must match this will be the error that will be thrown I'll render the error for the age for this gender and for these checkboxes as well so I'll say interests over here sorry this is the birth date so it should be over here and over here it should be birth date okay let's go back and uh let's make this first of all let's add some styling to this so I'll just take this error class name add it over here color will be red simple and yep you can see we have all of these errors over here let's add my name if I press on submit now you're going to see that particular error is gone now if I say my surname yep you see if I enter let's say password 1 2 3 4 5 6 7 8 9 0 very simple oh sorry this is phone number inide of password I'm going to keep the same and just in confirm password I'm going to remove the last digit so that these are not same so if I submit it so you see first of all it's giving us this error password must be eight characters long contain one symbol blah blah blah and this is giving us this password should match so you see this is how the custom validations look and you can Implement validations by using this long process or you can use something like yep which I'm about to show you right now now if you're enjoying this tutorial up until this point open your Instagram app right now and search roadside coder and hit that follow Button as hard as you can because I'm very active on Instagram and if you have any doubts any queries or just a normal message you can ping me on Instagram for this so go on do it I'm waiting what I'm I'm being serious over here open your Instagram app right now and follow me there oh you've already done it okay let's let's move on with this video so first of all let's go to Google and search react yep and over here let's open this npm package okay let's install yep so it's simply npm install yep so I'll just have a terminal inside of the terminal I'm going to kill the server and say npm install yep now meanwhile this is installing let's just duplicate our component let's just say form with yep I'm going to name the component as well form with yep and instead of this I'll just render that cool now we're going to make changes to this and I'll show you how you can transition from the previous custom validations to yep validations if something like this you know some requirement like this comes into your company you can easily migrate your code so let's just npm run Dev and let me show you how easy it is to use yep so if I go to the documentation and you can see we have created this schema over here which just defines what is the criteria for each and every field so for example for our name our name should be a string right self-explanatory it should be a string and it is required as well if the user has not entered it so you might remember we have added these conditions over here let me just close it yeah we have add these conditions over here that if form data doesn't exist if it's if last name doesn't exist so we don't have to add these conditions anymore we can just say do required that's it same for other fields as well which we will go on and write for each and every field for our code as well and then simply we're going to say await user schema do validate and I'm going to provide it the data over here and it's going to validate the data and it's going to return us a promise because this is an asynchronous function and then we can easily check we can you know handle the errors as well this in fact this handles the errors for us right out of the box which I'm going to show you so let's just go on right over here inside of our code and I'm not going to need any of these so let's just get rid of all of this redundant code so you see right now our code base is 281 line let's see how much we can reduce that so first of all Let's uh just remove all of these custom validations over here way too much okay ins start this validate form I'm not going to need that I'm just actually going to remove everything inside of over here here and yep now first thing is to import yep so I'll just say import Star as yep so I'm going to import everything from yep over here from yep so what you can do uh instead of this is you can have a curly brace and you can just you know import things from here like string required or whatever but I'm just taking everything over here from yep and I'm going to name it yep so now over here right below our error state I'm going to create a const validation schema just like you saw there was a user schema I'm going to create a validation schema and I'll say yep do object because this is an object right and start this I'm going to provide it an object and now here for each and every field I'm going to provide the validation so first of all our first name so our first name was string so I'll say yep dot string so it has to be a string obviously it has to be required as well and if it's not required so see right here we can just throw the error right away so if it's not present if the user has not provided us with the first name I'm I can throw whatever error I want over here so let's say if I say first name is required that's it if this doesn't meet the criteria it will just throw the error that first name is required similarly let's write it for last name as well for our email so email it's going to be different so email and do you remember we had to write that ugly Rex code right now I'll show you it's so much easier so I'll say it has to be string yep that's fine and it has to be required yep email it has to be required so I'll say email is required and right before this I'll just say it has to be an email and if it's not an email I'll just say invalid email format or you know what I can move it uh probably to over here yep that's better but there can be such scenarios where you have to add some rejects as well right like for example in our phone number so I'll just say phone number and I'll say yep do string yep it has to be a string and I'll say matches so matches will simply take a Rex expression so I'll just add a Rex for our phone number which is going to be this that it has to have 10 digits and if it's not the case I can throw an error over here that phone number must be 10 digits right what else this has to be required as well we need this after that for our password now let's see so if you remember if you go back over here we had this um ugly looking code where did it go yeah such a long code and we had all of this Rex Expressions right so now we already know it's so so easy to write Rex inside of this so I can simply say password and I'll say yep do string first of all it has to be a string then it has to to be required if it's not present I'll say password is required then first of all I want this to be minimum 8 digit long so you see yeah we had this password length more than equals to 8 right so I'll say minimum 8 digit long and if it's not the case I'll just give it an error of password must be at least eight characters and then it's going to be very similar to what we've added over here but over here you see if we had to give error for each and every of these that's not possible I mean it is possible but you'll have to add you know F else F else F Els over here but here we can add separate errors for all of these so simply see I'm going to say dot matches and it should have at least one symbol so I'll just add Rex over here and throw the error if it's not satisfied same with our you know at least one number at least one upper case at least one lower case so y That's for our password let's see for our confirm password so confirm password so basically confirm password needs to be same as this password right so I'll say yep do string do one off now this one off is useful for comparing it with this password so I'll just simply say yep. ref and I'll just add password over here so I'm I'm adding the reference to this password key inside of this yep object so I'm saying it has to be same as this if it's not same I'll say passwords password must match and over here you can you know in this one off you can add more values over here that this confirm password should match those values but in this case we only going to need this password's value and also this is required so if it's not present then I'll say confirm password is required now next for our age this has to be a number if it's not a number then I'm going to say type error age must be a number and age has to be minimum 18 and less than 100 so I'll simply say Min to be 18 if it's not then you must be at least 18 years old if it's more than 100 you cannot be older than 100 years and this is required as well so age is required next simply for our gender I'm going to say it has to be a string and it has to be required okay for our interests it has to be an array so yep dot array and minimum it has to have an have at least one interest or one single option and it is required yep and at last for our birth date it has to be a type date so that is also inbuilt inside of the yep so I'll say yep do date and it has to be required so yep you saw how easy it is to add validations inside of over here by using yep so let's see how we can use this inside of our handle submit so inside of our handle submit I'm going to say a try catch block because as I already mentioned this is a promise so I'll say a wait and since we're using a weit over here we're supposed to use asynchronous since it's promise that we are dealing with over here so I'll say validation schema. validate as I showed you in the documentation as well and I'm going to provide it the form data and this takes a second uh parameter of an object which takes a bunch of different things which I'm going to say abort early so I'm going to keep it false because what it does is as soon as it encounters the first error it just uh you know returns and it does not throw any more errors it just breaks the promise so we want to see all of the errors inside of our validation schema if any right so yeah that's cool if it's successful I'm going to say console log form submitted and I'll just render the form data form data over here and inside the errors so we're going to get bunch of Errors over here so if I say console log errors so let's go back and see so sorry it's going to be error if I press submit you're going to see we have bunch of different error errors over here like 16 errors but we have to format this so that we can read it so um where did it go instead of the handle submit I'm going to say error dot it has something called inner so now if I just press on submit again you're going to see now this gives us this validation error array with each of the object containing the you know information about each of these input Fields so let's say for example this one has the error for first name so see first name is required okay Okay cool so what I'll simply do is error do inner I'll take this and I'll first of all I'll say cons new errors just like we were doing earlier and I'll just populate it I'll say error dot inner dot for each I'm going to Loop through it I'll take each and every error and simply I'll say new error and service I'm going to get error do path so if I go back okay I have removed that I guess yeah see inside of it we have a path yep you see path is first name so for first name I'm going to say error. path the value will be the actual error that is this one or this message over here so I'll say error do message and yeah I think that should be pretty much it after that I'm going to say set errors the uh state that we previously created over here to be new error or I think it should be new errors that's much better and yeah let's see if I try to submit it now awesome we can see all of these errors now let's test it out so if I just enter my name and um let's say for our password I'm going to say 1 2 3 4 5 and submit so see it's giving us that password must contain at least one lower letter okay let's add the lower letter Q submit at least one upper letter okay let's add capital Q submit yep you see it it's asking us it should have at least one symbol as well let's add a symbol and submit it yep now it's gone so we have added successfully added the validation for all of these and you can go on and test for all of these as well like this should have a 10 digigit phone number this is required age must be between 18 like if I say 12 over here submit you must be at least 18 years old if I say 112 you you cannot be older than 100 years right if it's something like 19 it's going to be fine it's not going to throw any error right so this is how you can go on and add validations by using yep and you saw how easy it was now one thing that I mentioned that you can cast some values that if it's uh you know let's say string you can uh you know cast it to become a number so for example if I show you let's take a dummy data over here so before we submit this let's say I have this object which we have entered as values and see inside of this this age is a string but we want that um with respect to this validation schema I want this to be converted to number right so what we can simply do here is I'll say const first user to be validation schema do cast we can use this cast over here you can provide this nonp pared object now simply let's console log this and I'll say non pared and pared user both over here and now see if I try to submit it over here now you going see just forget about these errors first object was non first it had age of 18 with the string and in the second one you can see the age is a number now it doesn't have those a string inverted commas right over here and it did it with respect to this validation schema that we have already created right and if you go inside of our documentation of yep you're going to find bunch of different things inside of it and I would highly recommend you to go and you know explore more about it like we saw that we have this min max function for arrays for our date as well date can be minimum or maximum you can add validations over here so this is literally bunch of different things that you can explore over here which I would highly recommend you to go and do so y that's pretty much it if you like this video give this video a huge fat Thumbs Up And subscribe to the channel for more such awesome tutorials
Info
Channel: RoadsideCoder
Views: 21,415
Rating: undefined out of 5
Keywords: react, react form, react form handling, react form validation, react input validation, react form hook, react login form, react register form, react tutorial, react for beginners, form handling, best practices, useState, useRef, formData, react yup tutorial, yup form validation, react signup form, react js, react registration form validation, react hook form tutorial, react forms best practices, react forms, react forms with hooks, create registration react form, react yup
Id: 9rp_1TYDlkY
Channel Id: undefined
Length: 34min 13sec (2053 seconds)
Published: Sun Feb 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.