This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Validations Class

2:16 Angular 1.x lesson by

Now we bring the validations together with a Validations class.

Get the Code Now
click to level up comment guidelines


Now we bring the validations together with a Validations class.


One problem that I'm having with this series is keeping what you're saying... straight. What i mean is, its hard to visualize the code/execution flow of what's going on... when I'm writing code one thing I do to help other people keep track of how a class works is by creating a code flow diagram... which looks something like this:

The purpose is just to show a 1000ft view of how the code flows; just helps someone see the structure of stuff.


In reply to

Man 1: The next bit of functionality in our validatable library is a simple but necessary one. That's the validation. A validation is a combination of a configured validation function from the previous step.

Here we're configuring the main validator with a value of five, and the name of a field. The name in this case is actually just going to be Name, so we're going to validate the name of a user is at least five. This is similar to, again, using the syntax, user.validates length min five. Something like that.

We're going to, in this case, insure that when we use the min validation to validate this user, that we get the value true. If we set the name to an empty string, that we get a false value, and also that the min validation exposes the message from the validation function.

Right now, saving this out, we see that we have a failing test, because we have no validation class.

Let's go ahead and add this validation class. Under "Validatable," we'll create a home for this. Validation. We'll copy out some of this to make it easier for us. Instead of "Validator," we're going to say, "Validation." Right now, this relies on nothing.

There we go. Again, we just need to create a quick constructor for a validation, and we're going to return the validation. This takes, again, the field name and it takes a configured validation function. We're going to expose the public properties on the validation, so we'll say this.field equals field. This.message equals validation function.message. This.validate is a function that takes an instance and we're going to validate this instance by saying validation function and we'll pass in the instance, and we'll validate that field.

Doing this, all of our tests pass, as we would expect. Rather simple. 

Joel's Head
Why are we asking?