AJAX Validation in Laravel

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys Andre here and today I wanted to show you guys how to do ajax validation in laravel now this might not be the most practical way to do validation but might have some use cases for some of you out there I'll show you an example of where I got the idea from so if you're following my other series my laravel ecommerce series you'll know that I'm using laravel Voyager and they actually use it here on their back-end so I have a validation rule here that says it can only have max 5 characters so if I try to submit it there's some Ajax happening there and it highlights the validation rule and it shows the error message and this is coming from their Bell's end so we'll do something similar to this before we do that let me just take a second to ramble about the pros and cons of the different types of validation so number one is server-side validation this is absolutely necessary for all production apps you can't rely on front-end validation as malicious users can easily bypass that some of the cons are it's slow as it requires an HTTP request and it's not the most user friendly but again it's necessary for all apps so the way I typically do it is I have an example here so sorry that's the wrong URL so I have an example here and if I try to submit the form without filling it out correctly then we have server-side validation rules happening so the way I typically do it is I just have this code snippet and it just checks if there's errors and it puts it in an alert message box if you take a look at lera bells register I have the off scaffolding in place here you can get a bit more fancy with it so the error messages are sort of in line and they appear underneath the validation rule in question so let me show you what I mean if you go to register and let me just take out the browser or validation so let me just take this out and if you just look at how they structure the errors they'll put they're putting each error message within each field and they're adding a class if there is an error so it's sort of the Flex it sort of looks like front end validation and it's a bit more user friendly so if I just fill this up but leave the name out you'll see that there's a validation error actually after refresh you'll see that there's a validation error right there and it sort of looks like what a front-end validation system will would get for you but it's still on the back end for example if I put like just a whole bunch of text here and do the same thing I miss refreshes like it's not going to I mean it's gonna scroll up and it might be a bit confusing in terms of the user experience so I was gonna scroll up and again like the user might be confused as they have to scroll down to see the errors the next type of validation is browser validation this is probably the easiest to set up and it's built right into the browser so there's no need for JavaScript I typically do this combined with server-side validation and I'm assuming a lot of people uses as well because it's just so easy to set up one of the cons would be that each browser renders the errors differently so it might not look consistent across different devices and across different browsers so browser validation is just what we had here let me just remove this when you do like you add like a required attribute or if you do input type equals email like here the browser's automatically gonna validate that and it just makes it so easy there's even more things you can do take a look at this article from mdn you can even do things like pattern like you can specify a regular expression here and you can validate it right there so for example if I do that so it will only accept inputs net or banana or cherry and that's done for you already see that's not gonna accept it very fresh see please match the requested format and another type of validation is JavaScript validation where you use JavaScript or a JavaScript library to do the validation this is the most customizable and we'll have a consistent look across all your devices and browsers the biggest con is probably that you have to maintain two sets of validation rules one on your server and one for the client now this Ajax validation that we're gonna do sort of sits in between this JavaScript validation and server-side validation and the main pro of using this ajax validation is that we only have to have one set of validation rules on the backend level side and we can just piggyback off of that ok let's start so I'm gonna be using in this form which is very similar to the registration form I'm just using it because I don't want to create another model and also this has a few validation rules in place already like there's one floor required obviously and there's one for email and there's one for the password confirmation so I just have this create view and we need this anymore and like I said it's pretty much exactly like the register one but there's no layouts going on here and I also took out the browser validation here so it's all just input type equals text and there's no required attribute that I added if you look at my routes file there's only two new ones I added one for showing the view and one for responding to it so here's the controller just showing that view and here is where the user is actually created but I'm using a form request here to do validation and here's a form request and here are the validation rules so for the laravel validator if you look at the documentation if you look for 422 you'll see that it says if you make an AJAX request to validate something then it's gonna respond with a JSON response and a 422 HTTP status when you're doing it the normal way it's just gonna do a redirect response so in this case we're gonna catch that HTTP response and we are going to react accordingly all right let's finally write some code I feel like I've been talking too much so I'm just gonna be using vanilla JavaScript and some es6 and I'm gonna be using Axios to make the Ajax request so let's go ahead and do that so make a new script tag here I like to wrap everything in an invoking function and let's respond to the submit event for the forum so let's get query sorry user form that's the name of the form there's an ID on it so I'd event listener submit function E and me smoothi-- stop for you okay so what am I gonna do here I'm gonna prevent the default and now I'm gonna make an AJAX request using Axios let me just grab like this from Axios which is just some boilerplate and we'll just work on it from there I start in let me just reinvent this is it from here yeah reinvent okay so I'm gonna post to this dot action that's just the action of the form so if I go to the form so it's just this so I don't have to parse this this route helper that they're about using it's already I do that for us and the reason I used this syntax instead of an arrow syntax for es6 is so I can keep the context of this so it's the form and now we just have to pass in our data here and I'm gonna paste that in so you'd have to watch me do that and it's just getting the values from our form so our name our email or password and our password confirmation and we're just passing passing it in using javascript and this is if it's successful so for now we'll just console.log success and we'll work on that later I'm gonna make this arrow function and same with this over here for the error case which will be where most of our work goes so we can't just console.log the error because let me just show you actually let me open dev tools and let me try to make this bigger okay cool sorry make it bigger okay so if I just click this there is an error oh sorry yeah if I'm using the arrow function there should be no function keyword so let's try that again so if I do this okay so it's logging the error but I actually want the response from the server so to do that we can console.log error dot response and then you'll see the structure of the data coming in from the server so if you try that again so there's a data right there cool and if we go into data and there's a section called errors we can see that the errors come in as an object and each field has an array of error messages so let's do something like this it's coming so let's save that error that response dot data thought bearers so we'll just we're just following this structure that came in from the server okay and let's just see how that looks okay cool so I'm only gonna be handling one error at a time and what I wanted to have happen is just grab the first error and scroll to it and show the message as it comes in so whatever the error message is I just want this first one but since this is an object I can't just get the first one so let me show you what I want to do here I'm just gonna use and I call another variable called first item and you can use this function object lock keys which will change the object to a array so I'm gonna change that and then I'm gonna get the first one and that's gonna return just in this case it'll return email or whatever the first error is so let me just console.log that okay cool actually no that's wrong let me just refresh okay so the name and then if I put something in here then this should be email and it is cool now we also want the Dom item associated with that so we want like for example we want this textbox associated with this and I structured my HTML such that the name I'm sorry the input ID and the input name are the same so here's what I'm going to do I'm going to make another variable call it first item Dom and send a document dot get element by ID and that will just be that first item with yourself and we also want one more thing sorry we also want the error message that comes in so make one more variable story there's a lot of variables here and this is going to be that first item that we got and the first item come in I hope that makes sense and now we have everything we need so all we have to do is two things we want to scroll to the error message and we want to show the error message so let me just put some extra stuff in here so when we hit this button it actually Scrolls to the error let me just put some crap in here but form group lorem 500 see how that looks okay cool that's cool so when I click this and there's an error I wanted to scroll to the field with the error okay so let's go ahead and do that so scroll to the error message how are we going to do that well I actually just learned that there's actually a native method that does this in JavaScript and that native method is called scroll into view so we already have that done so first item Dom and we just call that method scroll and you can see we have schoo knows about it and we can even do something like this the behavior smooth so it sort of Scrolls to it smoothly and that should scroll to the error message just be careful if you do this because the browser support it's pretty good but it doesn't work for IE just take a look at the mdn for this method so let's see if that works so I wanted to scroll here there's gonna be no error message because we haven't done that yet better see if that works and it does cool let me also put some stuff on top of that just to make sure it's working just on top of the card here save this work actually that's one see if it's scrolling to the right place and not just a talk I think it is just I don't know why it's scrolling a bit extra let me remove this behavior smooth like that you don't need that see if it works now okay let's go leave like that okay so the next thing we want to do is show the error message so what I want to have happen when there's an error message I just want to add another Dom element like for example for this one if there's an error on the name I just want to add another one like right here I think there's a class in bootstrap called text danger now make it read ever close here don't mind my spelling see how that looks okay so that's what I want so let's go and do that okay so first item Dom there's a method called insert adjacent HTML and the first parameter is just where you want to go so after end and the second parameter I'm gonna use template strings here they've class equals tax danger and I want to put that first error message in there and close the div and close my template string all right and see if that works okay here we go the name field is required but if I fix this this is not gonna go away and we have to make sure that goes away see it's highlighting the correct field now but that one never went away because it was there from before so let's make sure we remove all the ones from previously so remove all error messages and I'm just gonna do a for each loop document it's gonna grab all of them document query selector all and all of them are gonna have the class with text danger on them so let's grab all of those and error messages up for each and it's going to do this with an arrow function and we're gonna clear that element top text content equals blank that should do it go check so air at first okay right clear it and do the second error cool that one's fun awesome I also want to highlight the text box so just put a red border around this so let's go and do that just make another section highlight the form control with the ever and that's simply enough it's similar to what we just did so first item dom we're gonna add a class we actually have to add two classes one is called porter and this is just default bootstrap for when the elements called bootstrap i'll sorry boarder danger and that should do it but we also have to do the same thing and remove all the previous ones so remove all form controls with highlighted errors text box okay so same thing const form controls equals document not query selector all and we're just grabbing all of the form controls and form controls for each element arrow function element dot class lists that remove border and border danger let's see if that works so let's see if it highlights it it does fix it next error see if it removes it and it does cool all right let's look at what happens when we actually fill out the form correctly so let's make a new user password password we should see a success message so let's see if that works okay success and this should have hit the route so our user should be created so I should have hit this route and this should have been executed but since it's an AJAX request nothing's gonna happen when we get to this line I should see if that user went into our database and it did but we want to have like a flash message so I'm gonna do this instead and I carry this oops and then I'm gonna do session slash success message and user successfully created and this is essentially doing what this just did and we can return some JSON if you want you not do this but it looks clean if we do this success true okay so now let's see if it refreshes the page and we get this if we put in some details for a user okay one one one comm password password let me show you if the two passwords don't match let's make sure that case works and it does cool and let's see if this refresh is oh I didn't then i refresh oh I did not well I still have to do something in the front end so I have to refresh the page on my front end here so window.location.href equals and since we're still in a blade view we can actually just do this and hopefully that works let's try it again that user went through it so I have to make a new one yeah let's make another one its refreshes oh okay see now it's coming through now you see that flash message but let's do it one more time to - at to comm password password and there we go that worked check the database if two is in there and he is cool obviously this should be hashed so doesn't matter cuz I'm not logging in but in here I should specify for the password to be hashed let me just do that quickly actually bcrypt and that should be better let's give it another shot three three three comm password password cool user created successfully let's check the database and it's correctly hashed cool we can also do the positive case in a more sort of like single page app style where we don't do this but in our JavaScript right here instead of refreshing the page money does anymore like so we can reset the form so just we'll just clear out the form fields and I can just insert any message so some I told you before after and let me just do a div class equals alert alert success and form submitted actually a new user created successfully and close the div this should work as well but this time we're doing it in a sort of single page app style where the page does not refresh okay I mean try this again so for for at for calm password password and yeah we can scroll down but if I scroll down there this year I put it here because usually people click but you can work on the scrolling and see if that person is in the database and they are cool okay I added the scrolling all I did was put an idea on the success message and I just scrolled to it like we did before okay next thing I want to show you is custom error messages so since we're getting our error messages from laravel we just have to change the error message here in our user request so I'm gonna paste in a new method called messages and it's just going to return an array with your custom error messages so for example for name dot required name not required here you can put in your custom message there and I went for email email and you can do for any validation rule you like so let me save that refresh this and this should have the new custom message and it does there you go put that in and there you go the email field is required I thought I customized that oh yeah I have to put that first and then now I should have it there you go also make sure for email you want to make sure that it's unique because if you enter an email that already exists then there's gonna be an error so make sure you have this validation rule as well so let's put unique on the used users table yep and this should automatically work when it's refresh this and I already have this email in the database and it's this should have a proper message there you go so there you have it guys we managed to use Ajax validation from within they're able to give our application a slightly better user experience like I said before personally I don't do this I usually combine server-side validation and browser validation but I might consider this in the future as an alternative to using a JavaScript library for validation a part of me wants to extract this code to a laravel package so someone can just drop it in to a project and have instant Ajax validation there's actually a few packages that I found that do something similar but I'm gonna do more research and if it's not as simple as what I'm trying to do then maybe I will extract you a package if you're watching this in the future just check the description below and if I do make it I will link it there please like comment and subscribe if you haven't already done so thanks for watching guys see you in the next one kay thanks bye [Music]
Info
Channel: Andre Madarang
Views: 21,247
Rating: undefined out of 5
Keywords: laravel ajax validation, laravel ajax form validation, laravel ajax form tutorial, laravel ajax, ajax laravel, laravel validation, validation laravel, laravel form request, andre madarang, drehimself, ajax validation laravel, laravel axios ajax, laravel axios
Id: 10uUnaKgVeo
Channel Id: undefined
Length: 32min 46sec (1966 seconds)
Published: Fri Mar 02 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.