Form Validation in React Material UI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi all welcome back to the complete react material ui tutorial so this is the fourth video in this series of videos where we discuss how to implement form validation and how to insert a new record inside the form submit event validation will be done for and therefore as a whole and and also we will do the validation for single control for each key press finally after successful validation we will insert a new record into data storage before starting this video i would like to thank for your paypal donations for my previous works in order to make more helpful and quality tutorials like this you can also support me through paypal donation have given the link in video description and inside the first comment of this video so without further ado let's get started with this topic here we have the final output from previous tutorial where we have discussed how to create or design a material ui form with all common input controls all of the video links from this series will be there in video description and inside the first comment of this video so in this tutorial we will cover everything related to material ui form validation so these are the validations that i am planning to implement here this full name should be mandatory email is not mandatory but if there is something inside that it should be in proper email format in case of mobile there should be more than nine numbers and finally there should be one department selected for the employee so let's look how to implement these validations so here we have the same project that we have left from previous tutorial for all of the controls inside the form we have used reusable components that we have discussed in previous tutorial we have created the text field for these controls full name email and mobile so which is the inside this component input with the help of material ui component text field now let's check what we have got inside the material ui documentation here as per the documentation here with this error property we can toggle the error stage and with the help of this property helper text we can show this feedback here for example let's check this example here so let me expand the source code so here we have the corresponding text field first of all we have to set this property error as true for showing the error and corresponding error message will be the inside this property helper text we could do the same inside this text field also first of all we just need to set this property error and then helper text inside this property we will be showing some validation error now you could see the change inside this form here all of these text field components are in error state is below that you could see the error message now let's look how to implement validation as per our requirement we have designed the form inside this employee form component here so first of all i'm gonna define a function for validation so here is the function validate for now we don't have any parameter for this function first of all we have this input control for full name it is mandatory to submit this form so let's look how to implement the required validation for this control full name for that first of all i will define an object like this temp inside this temp object we will be saving the validation error message so we can do this temp inside that we will have this property full name here we will check the value of full name property inside the state object values as you know this form is designed with the values state object here so we can check the value of full name inside this object if there is a value inside this property we don't have any error message so i will pass the empty string here we are doing that with ternary operator otherwise we will have this error message this field is required like this we have to add three more validation for email mobile and department so i will duplicate this line three times using the shortcut ctrl c then ctrl v now let's define the validation for email property it is not mandatory but if there is any value inside this text box here it should be in proper email format for that i will be using a simple regular expression here the expression starts with the forward slash here we can allow the user to leave this field empty so we can use this dollar simple here and here we have the o operator meaning if there is something inside the text box it must have one or more character before this at the rate simple and then one or more character followed by a period simple after that also we need one or more character so this is a simple regular expression for checking email address we will end this expression with the same forward slash here and we can call the function test inside that we have to pass the email property if the function returns true meaning this field is valid otherwise we will show the error message email is not valid after that we have mobile before mobile property we need at least 10 characters so we will check the length property here it should be more than 9. otherwise we will show this message minimum 10 numbers required and finally we have this department drop down here we have designed that with this property department id selected department id will be stored inside this property here so we can check the property department id so let's do that here by default it will be an empty string so we can check that here with the length if length is not equal to 0 we will show the same error message this field is required so inside this function we have defined the validation for form controls and we have saved the error message inside this object temp we have to have a component state property for saving these error messages that we can do inside this component used form but we have defined the values object here just below that i will define the errors object also so let me duplicate this errors then set errors initially it will be an empty object like this and from this function use form will return the object errors and set errors we can access that inside the employee form component here errors then set errors now inside this validate function we can save the errors from this object into this state object arrays here so that we just need to call this set arrays function and inside that we can have this object with the help of separator operator we can save those error messages into the errors state object now we have to call this function somewhere inside this component we will do that while submitting this form here we have not yet added a submit event for the form let's do that here for designing this form we have used this reusable component form this is not the html form we have created a reusable form inside this file here used form we have discussed various benefit of using reusable component inside the application in previous tutorial now let's look how to add the on submit event for that i will just add the on submit event here on submit is equal to we will be defining a function handle submit okay let it be here handle submit for now leave this function as empty now this is a reusable component into that we have passed this property on submit we have to assign this into this html form here for that we can use the destructive syntax like this first of all we will have the children property so children this children property refers to the child component inside the form here and rest of the properties will be the inside this other property we can use this separator operator here and we just need to assign the props here so the on submit property that we have passed here will be the inside this other property here now we have to assign that into this form here for that we just need to do this other now if you want to check whether this event works or not we can call this alert function here let me save this back to the application submit before that's it now let's call this validate function inside the form here i will do that inside this if statement here validate so this valid function must retain a boolean value indicating whether the form as a whole is valid or not for that we want to modify this function a bit we will have this return statement first of all and then we can call this function object dot values into this we just need to pass the object temp so this values function returns a collection of values inside this object which are email full name mobile and department and from that return collection we will call this function every inside this function we can have this condition if this function is new to you you could check this mdn documentation here the method test whether all the elements inside the array pass the test implemented by the provided function so so if all of the properties inside this temp object is an empty string then we could say that this form as a whole is valid if this condition is true for all of the properties inside the object then it will return true otherwise it will return false and thereby we could see this alert here let's check that here don't look at this uh error messages we will fix that accordingly now let's try to submit this form currently when we submit the form this page get reloaded we don't have to have the default behavior of the form so it's there inside the html form by default so let's prevent that for that we can have this default parameter e and then we just need to call the function prevent default let's try that again now we can't see this eyelet here because this function returns false all of these properties are not valid so let's try after populating these form controls here email is not mandatory so let's move to the mobile number there should be at least 10 numbers inside that let's select a department here submit the four that's it since we are getting this alert message here the form as a whole is valid now let's remove the selection for the department here submit the form now we can see the alert message since we have some validation error regarding this department so we have properly defined the validation with this validate function here now we have to show validation error message along with respective controls here so first of all let's show error messages for these input controls full name email and mobile after that we will do the same for this department select drop down here so back to the employee form into these controls full name first of all i will pass this property error errors dot full name we have designed this control inside this reusable component input here we don't have the property error that we have passed here so let's add the property here error i will set null as default value here now into this component here we have to set these properties error and helper text dynamically based on the helper message that we have passed from the form if there is a value for this error property we have to apply these both properties inside the component here for that we can do this first of all we will have the curly brace and we can use this separator and then we can have this pair of parentheses first therefore we will check this property error if this property is not null then we will do the rest of the operations so we just need to return this object containing these properties error and helper text so i will do this error is equal to true and then we have the helper text which is the inside the property error that we have passed from the form so first therefore we will check whether the property is not null or not if it is not null then we will return this object containing these two properties error and helper text and that will be separated here so that these properties error and helper test can become a part of this outer component here now let me remove these properties from here sorry here we have to use two and simple let me save this and back to the application let's check whether it is working or not now let's submit the form without full name boom so here we have shown the error message for full name now let's provide a name here submit before now it works now let's do the same for this email and mobile also now let's pass this property for email and mobile back to the form submit this that's it it's okay to leave this email as empty but if there is something inside that it should be in proper format let me enter some random text here submit the form now it's not working there should be some error related to the email here let's check the regular expression that we have passed here yes here we miss this and simple upward arrow or you could say the carrot simple so these symbols indicates starting and ending of a string respectively in between them we don't have any character meaning it allows empty string now back to the application let's try that again submit the form now we have the error let's add the domain here at gmail.com submit the form now it's working now let's look how we can show validation error for this select drop down here as per the mui documentation here in order to show the violation error for select control we have to set the error property for the outer form control in order to show this helper text we can have this component form helper text just after this select component here and so based on the component documentation whether it is text field select control or date picker whatever it is you could set these properties dynamically now let's look how to show these properties error and this component form helper text inside this application for this department when it is not valid so first of all we have to pass this error property here errors dot department id now back to this select component here first therefore we will add this property error here i will set null as default here now first of all we have to set the error property like we have seen here error i will do the same like we have done here with the help of this and operator so let me copy paste the line here we have to set this property error as true now let me remove this helper text from here now let's show this component tag form helper text dynamically for that let me copy this from here we have to add that just below we select control this mui select is also the same select control that we have seen here we have just used this alias mui select so first of all i will have this curly brace if the value is present inside this error property we can have this tag form helper text we can show the error message from the property error now let's add the import statement for this component form helper test you can use the shortcut hold ctrl then press space most of the time the auto suggestion without default works so i will select the second one here so here we have added the import statement now let me save this now let's check whether it works or not submit before that's it here we have the error due to department now select one department here submit the form now we don't have any department validation error so that's how we can implement form validation as a whole currently we validate the form only when we submit the form we have to do the validation for single controls on each key press here so we will do that in a bit before that let me reset the form so back to the application let's define a function reset function inside this reusable component use form here so here is the function reset form inside this we just need to clear these state objects values and error so i will call the corresponding functions set values inside that we could pass this initial field values we have discussed them in previous tutorial and then we can call this set a risk function into that we can pass this empty object and now let's return this function from this component and let's access that inside this form here because of the reusable components that we have created in previous tutorial we can just reuse them by calling this use form function like this now let's set this function into this reset button here we have designed that with this reusable component button which is here inside this component we have this property on click for click event so we just need to pass that function here on click we'll just pass the function reset four so this on click function will be assigned to the button mui button here now let's try that here let me enter some random text here submit before we have values and error message inside the form here now let's reset the form boom so it works as expected now let's look how to implement single control real time validation as you might have guessed in order to do that we have to call this validate function inside this on change even of input controls we have defined this function handle input change inside this reusable component use form here so first of all into this component i will be passing two properties here validate on change meaning whether we want to implement single control validation on real time or not so that you can skip this feature for some forms i will set the default value as false here and then we can pass the validate function that we have defined inside the form component here so while calling this function useful pass true4 on change and then we have to pass this validate function here so we want to do the single control real time validation using this validation that we have defined with the function validate for that we have to do some changes inside this handle input change here so first of all we will check whether this form asks for this feature for single control validation so we can check that with this property validate on change inside that we will call the function validate that we have to define in corresponding form component like employee form into this function we are going to pass an object so inside this object will be having a single property name it will be replaced by the control name property from which on change even is triggered that will be similar to the name that we have passed here and value for this property can be accessed from this value here now inside the function validate we have to make few more changes i will add this new parameter field values by default it will be having the values object that we have here so when we call this function validate from this handle submit event here even though we are not passing anything here this parameter will be having this default value values containing all of the properties that we have here with respective values now we have to add this if statement for each validation we will check whether this property full name is the inside this feed values here in field values so this is required for single control validation from this handle input change here we are just passing an object with a single control value so we only have to do the validation for that particular control we have to do the same for rest of the validations here email mobile and department id so the call that we have made inside this submit event here will be same as before all of these validation will be done since all of these properties will be present inside these field values here for single control validation we have to do only one of this validation that's why we added this if statement here in that case if we assign this stamp object with an empty object like this it will clear existing errors inside the form in order to avoid that we will save the existing errors inside this temp here errors and based on the property that we have passed it will only update that property for the error message okay and finally we just need to return this boolean value indicating whether this form as a whole is valid or not so we have to return this boolean value only when when we call this function inside the form submit event here in order to identify whether we are calling this function from handle input change or submit event we can have this if statement here and we will check whether field values is equal to values or not so i hope you understood everything that we have discussed here if you have any problem in understanding or implementing these features in your application let me know in comment box below now we have done everything for the single control input validation let me save all of these modifications let's check whether it is working or not let's submit the form without any value now let's check whether single control real time validation works or not it's not working as we expect but it works as we keep entering the reason is pretty much basic inside this handle input change function here we have updated the values object here but this values object will not be updated immediately after calling this function here it is an asynchronous function which is mentioned inside the react documentation here i have given the link in video description you could check that also there will be a small delay because this operation is done asynchronously in back end so we can't depend on this value state object inside this function validate which is called just after this update set function here so this update operation won't work immediately after calling the set values function there will be a delay so that's the reason for the issue that we have seen here just immediately after calling this function we are calling the validate function inside that we are testing or checking the value from the values object so this operation will be done before updating the value of the property so in order to avoid this problem we can use field values instead of values object here now this should work as we expect the value for this parameter field values is passed by directly accessing the value even target here so it will provide the current value now let me enter the first character here boom it works now let's try the real time validation for rest of the controls here currently this email field is not valid let's complete that with a proper email format email gmail.com now let's try the same for mobile and for the department also submit the form so here we are getting the alert message meaning this form is valid now so that's all about form violation in next video we will discuss how to work with data table in material ui in order to demonstrate material ui table with paging sorting and filtering we need list of employees so before winding up this video we will insert new employees inside the form submit event here to store this list of employees i will be using the simplest and easiest method for data storage which is browser local storage instead of some backend apis like asp.net core node.js php etc if you don't know don't worry you just need to know these three functions here set item get item remove item so from this local storage object here you just need to call this set item function in order to insert a new data as a first parameter here we have the key and then the value as a second parameter so for example with this mycat key we have stored tom in order to achieve this you just need to call this function get item with the particular key that we have passed while inserting the record and finally in order to delete the item we can call this remove item function with the key now back to the submit event here inside this submit function here we just need to insert a new employee from these control values here for that first for inside this employee service file here let's add corresponding local storage functions so first of all let's define a function for insert operation insert employee with a single parameter data containing the form field values so inside this function we just need to call this function set item for inserting that particular object so we'll be calling the function like this local storage set item as a first parameter we have to pass the key where we want to save the list of employees so it would be something like uh employees and then the object that we have received through this parameter data so before saving this object json object into the local storage we have to convert that into json string so we will be calling this function json stringify here and into that we can pass this object data now as per the best practice it is recommended to store this string here inside a constant variable so that we can avoid the mistakes of typing this string in various other functions like retrieve or delete operation so we can do this define this constant object here keys inside this object i will have this property employees inside that we can store this string here now we just need to do this keys dot employees now before defining this insert operation let me define the function for retrieving all of the employees records that we have saved inside the key employees so here is the function i will just paste that function here get employees first of all we will check whether that particular local storage item is already occupied or not if it is null we will insert an empty array into that particular key and finally from this function will return the array of employees now inside this insert function here first of all i will retrieve all of the employees you can call this function get all employees here into this area of employees we can insert the new record like this just call the function push from the array and we can pass this data here now instead of storing this data record into the local storage we have to save this employees array here so employees now before inserting this record into local storage we have to have a unique primary key for this data here inside local storage along with list of employees will be storing the employee id for next insert operation so here is the key for that data employee id so this is similar to the primary key that we used to have in our practical databases now before this push operation here we will generate a unique id for the record we will save that with this property id to generate the particular id we will create another function here generate employee id so inside the function we will just do this so first of all inside the function we will check whether that particular local storage is already occupied or not if not we'll save zero inside the local storage here now inside this id we will be retrieving that particular id that we have inside the local storage with the employee id key and then we will increment the id by one and we will store that back to the local storage and finally from the function we will return the incremented id and that we can use here generate employee id function can be called here so that's all about so that's all about the insert and retrieve operation here rest of the update and delete operation will be done in upcoming tutorials sorry here we have a typo with this function generate employee id we have the extra j here so let me remove that and also we have to enclose this id parameter inside single quotes like this now let's call this insert function inside this employee form submit event here we have already imported that particular file up here employee service now let's call the function here insert employee into the function we just need to pass the value of form controls for that we can just pass this values state object here back to the application here now let's insert a new employee finally submit the form now to check whether we have inserted the record into local storage you can do this first of all go to inspect then application then inside that you could see this local storage here boom so here we have save the employees and employee id as per the form that we have given here after this insert operation we forgot to reset the form here and we can do inside the form submit event here reset form so that's it guys in this video we have discussed how to validate a react material ui for and after all we have inserted the employer code into local storage in next video we will be dealing with material ui data table with paging sorting and filtering if you found this video helpful please thumbs up this video and for more awesome videos like this please please subscribe to this channel coder fiction please like and share this video with your friends and colleagues so that they can benefit from this have a nice day bye
Info
Channel: CodAffection
Views: 46,915
Rating: undefined out of 5
Keywords: material-ui form validation, react material ui validation, validation best practice, validation with react hook, insert new record from submit event, validation in react js, CodAffection
Id: 4YLa9iuN43c
Channel Id: undefined
Length: 34min 18sec (2058 seconds)
Published: Tue Jul 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.