How to Validate Forms in Angular
May 5, 2017 11 min read
Transcript
Hey everyone Nic Raboy here we're going to take a look at validating forms within an angular web application so as you can see I do have my terminal up I also have the angular CLI installed and while you don't need the angular CLI installed to be successful with this project it will make things a lot easier so what we're going to do is we're going to create a new angular project I'm going to say ng new validate project and hit enter so as of right now my project has been created it is on my desktop so what I can do is I can say CD validate project I can open that project this is of course generated by the angular CLI so if you didn't use the CLI it'll look different but I do highly recommend that you use the CLI I'm going to go ahead and open this project in an editor of choice I'm going to be using atom by github for all of this coding you can go ahead and use anything you want whether that be Visual Studio code or something else so my editor is open we're going to be spending a lot of our time in two particular files so if you go to source app we're going to spending a lot of time in the app component HTML file and the app component dot TS file for typescript we're also going to be creating another file later on but this for now I will keep us covered so we're going to start off in the HTML file we're going to create a very basic form which we're then going to validate so it's going to remove this and we're going to say form and we're going to say no validate and the reason why we're doing no validate is because by default html5 has its own validation through the use of little popovers that's not particularly useful in most scenarios so we're going to we're going to turn those off so we can actually use the angular validation so now we're going to create our form element so we're going to say div and you can create these however you want it's just a very basic example we're going to say label 4 equals email so we're going to have an email field so we're going to say input type equals text we're going to leave it at that for now we're going to we're going to clean this up and we're going to go through it together on on all of the steps we're also going to copy this and I'm going to create another field called save password and call this password and this is going to be masked through password so we have two two input fields and that's enough for this particular example so what we want to do is we want to make this more or angular like so we can start off by adding a template reference variable in angular so let's go to name this email and we want to be able to use the angular ng-model directive and we want to be able to use that so that way you can access certain features like the errors that might exist in the form and things like that so that way validation is possible so we're going to use ng model we're also going to give it a name so we're going to call it email and we're going to give it a bind point so we're going to add some data binding so I'm going to the ng model equals and we're going to say input email now we haven't actually created input email so if we jump over to the app component PS file we can remove title and we want to say public we want to say input that's going to be of type any we're going to say public constructor then we're going to say this input equals email and that's just going to be an empty string so going back into our HTML file what we also want to do is we want to do a similar thing for the password field as well so we can jump down and say password or name it whatever you want really ng-model we're going to give it a name equals password we're going to give it a binding ngmodel we're going to say equals input dot password we're going to jump back into our typescript file we're going to add another property here and the input object we're going to call it password I'm going to hit save so let's go ahead and see what we have up until now when we build this application so we're going to go back to our terminal we're going to say NG serve so disserving so if I go to my web browser and I go to localhost 4200 I do have two fields but to clear this up we probably actually want to have a button too because in the realistic scenario we'll have a button as well and we'll see how validation plays a role in that as well so we're going to say button that's going to be of type equals button and we're going to call login because this is going to be a very basic login form even though we we don't actually add any login functionality the goal here is just validation of these input fields so we do have these template reference variables we have it bound to our tight script now what we want to do is we want to be able to catch any kind of errors but we're not actually validating anything as of now so we want to say is let's say this form is required this element we're going to say the password is required as well but we're also going to say that the minimum length in order to be valid is going to be 5 characters so this is all part of HTML this is not Angela so what we want to do now is let's go ahead and add messaging if there is some kind of problem so we can say div and this is where all of our errors are going to end up but we're going to say ng-if so if we're going to say email dot errors so if that errors property exists on our email reference to our template and so we don't just want errors because by default our required fields while they're going to be aired because as soon as we load our page there's no data in them so we want to say and email dot dirty so the dirty property means that we have actually touched error actually started using this particular field so we've entered a character into this field so we're saying if there's errors and we've actually started using this field or maybe there's a scenario where we where we give them the fields focus but then we go on to another field we haven't actually entered any characters in so we want to say is dot touched so this means that the field was blurred so if those conditions are met so either of those two plus they're being errors then we can say P so for paragraph ng if equals email dot errors dot required so if required is throwing an error then we can say email is required and hit save so let's let's see if this works as of right now I am serving so it is it is rebuilding every time I hit saved I can go back to my my form here I'm going to give it focus I'm going to lose focus so you can see that it now says email is required because there's nothing there if I add a character in there it went away even if I lost focus but or I can go backwards I still have focused it's because it's dirty that email message is still required so let's go back into our code we're going to expand upon this a little bit more so we're going to say let's just copy lines 5 through 7 we're going to paste it in for password we're going to change anything that says email here to password and we're going to say password is required and if we save it we can double check this lose focus password is required but we're actually checking for two different two different items here we also want to check to see if the minimum length was met so what we can actually do is we can say let's go ahead and just clone this line we're going to say if password dot errors dot min length that means that min length is throwing an error so we're going to say password must be 5 characters or more so save it go back to our form let's go ahead and type 1 2 3 4 5 the error went away so just like that we we got a little further so that's that's very useful information if I clear this field says password is required so now let's go ahead and take the step further we don't want this button to show unless there are no errors so we actually need to add a template reference variable to our form so what we can say is hashtag form or whatever you want to call it doesn't matter equals ng form so we want to use the directive ng form so that way we can look into any errors that might exist so in the button tag we can say disabled and we can say equals form dot invalid so what does this mean so we're saying if form is invalid meaning there's any kind of error this disabled will be true and that means that it'll be grayed out so I'll go back it's currently grayed out because the form itself has errors even if we're not displaying them remember these two fields are both required but we're not showing a required message unless we lose focus or something so as long as we can meet those requirements this button now becomes undecidable or active or enable whatever you want to call it so that that's all good for for form validation we did very basic stuff based on available HTML attributes so what about if the scenario comes along if maybe we want to create our own kind of validation so we can actually do this in the form of a directive and if we open up our terminal we can use the terminal and the angular CLI to generate a directive for us so let's stop serving we're going to type in ng G for generate directive I'm going to say let's just say email validator does it doesn't really matter what you call it so if we go into our project two new files were created a spec file for tests and our typescript file which is where we want to spend most of our business here so what we want to do is we want to add a custom validator and this validator will actually check to see if our field is an email field and I understand that if we wanted to we can say that the type was instead of text email but we're going to for demonstration purposes we're just going to assume it's text but we're going to validate through a directive instead so we do need to add a few things so we need to add a few imports here so we're going to import ng validators validator and abstract control and these are from angular slash forms we need to add various providers to this directive so for example we want to say provide ng validators we're going to say use existing and we're going to say that we're going to use existing and it's going to be email validator directive I'm going to say it multi is true and this will allow us to create a directive that's also a validator on our form and we're going to save it so far so we can leave the constructor as is so we're not going to actually use the constructor but we're going to create a method here we're going to say public validate we're going to pass it a control it's going to be of type abstract control and it's going to return a key string any so this is all part of the angular documentation and the reason why it looks like this is because this is actually going to implement it's going to be an interface implements validator so let's go ahead and take a look now so our goal here is we want to return either no in this case no would mean that there is no issues with our form otherwise we want to return some kind of key and a message so let's go ahead give it a shot it's going to it's going to show these errors for a little while I think I misspelled this implements validator but it's going to show some errors for a while our goal here is to validate our email with a regular expression and I'm going to say let reg X equals and now I am NOT a regular expression master so what we're going to do is I'm actually going to rip off a regular expression from a website that I know of called email address regular expression 99% I'll include its email regex comm they provide a very nice JavaScript regular expression that we're going to use just copy and paste it and what we're going to do now is I'm going to go to the next line we're going to say let valid equals email reg X dot test so what we're going to do is we're going to test a string value to make sure that it passes this regular expression and the string value is going to be whatever is in that field so it's going to be control dot value so the control dot value is whatever that whatever field this is attached to finally we're going to say return and we're going to use a ternary operation we're going to say control dot value is less than one so that means that if if it's less than one or it's valid so if it's true that means that we're going to just return null and we're the reason why we're saying less than one is because if there's nothing in the field we're going to assume that the email address is valid even though there's nothing there and you can optimize this however you want we're going to return null if it's true otherwise we're going to say let's for say for example email is true so you can see the errors went away this time so in order to use this directive you actually use this email app validator right here that's the name so it's kind of it's kind of long oh not necessarily a very attractive directive so we're just going to call it email so now if we wanted to we can go to app component dot HTML and we can add it on so we're going to say email that's the directive because that's that's what we just called it we're also going to add another if statement so we're going to say if email because remember if we go to our directive again we this error is email which we're also providing here it looks a little funny but that's just how we set it up so we're going to set email is not valid and hit save so let's go ahead and look at our code not our code our build project is it running no it isn't so let's go ahead and run it and you serve perfect so we'll go to our browser go to our project will refresh the page let's go ahead and say test so it says email is not valid at test dot Co so that's that is technically a valid email it has it has an address after an @ symbol so if you understand regular expressions grape you'll be able to understand what all of this does to me it's just one big nightmare but we're testing this field based on a regular expression which is pretty pretty cool so if I were to wipe it out again it's required and it's not valid so we just did a whole lot inside of this small demo there's not we didn't do a whole lot of code but we accomplished a lot in terms of what we did so we learned about the using template reference variables that use directives so the ng model and ng form so that way we can look at whether or not they contained any kind of errors and we use the various properties that are available inside of ng model so for example there's dirty there's touched there's also a few more so there's valid invalid pristine they all be various things that you can find online but if any of those are met we display the errors on the screen but more cool is what we actually did with the custom directive we were able to create a form validator that used a regular expression to determine whether or not our value was a valid email address
Up next
Lorem ipsum dolor sit amet, consectetur adipiscing elit.