Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Validations Class


    Now we bring the validations together with a Validations class.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.