Skip to content

Validating Values

Charl Gottschalk edited this page Jul 21, 2016 · 12 revisions

Validating values with ApproveJs is easy.

To run a test, ApproveJs exposes a single method called value() that requires two parameters. The first parameter is the value you wish to test, and the second parameter is an object containing the rules you wish to test against.

approve.value('value', rules);

The Rules Object:

The rules object is how you will tell ApproveJs to test your value. It is a simple object containing the name of each test to perform as a property, and it's constraints as it's value. For example:

var rules = {
    test: constraint
};

Let's pretend we want to approve a value against the email and required tests.

var rules = {
    required: true,
    email: true
};

var result = approve.value('user@domain.com', rules);

The above code will check whether the value is present (required = true) and whether it is a valid email address (email = true).

You'll notice we only passed a boolean as the constraint for the required and email tests. That is because the require and email tests expect no parameters. We could have also passed in a string or integer and the result will be the same. For example:

var rules = {
    email: true
};

will do exactly the same as:

var rules = {
    email: 0
};

or:

var rules = {
    email: 'doodoo'
};

As long as the test expects no parameters, any value will be treated as if it means to perform the test.

Some tests, however, expect one or more parameters. For instance:

The min test that checks for a minimum length, expects a single parameter, an integer value to test against:

var rules = {
    min: 5
};

var result = approve.value('This text is longer than 5 characters', rules);

We could also pass in the parameter in an object, and ApproveJs will correctly pass the parameter to the test, for example:

var rules = {
    min: {
        min: 5
    }
};

var result = approve.value('This text is longer than 5 characters', rules);

That will do exactly the same thing, although, that seems a bit redundant. But hang on, there's a reason for that. Custom error messages.

For tests that expect more than one parameter, an object containing those parameters is required. For instance:

The range test that checks whether a value has a minimum of n characters and a maximum of n characters expects two parameters, min and max. For example:

var rules = {
    range: {
        min: 5,
        max: 20
    }
};

var result = approve.value('This text is longer than 5 characters', rules);

If an expected parameter is not present in the rules, ApproveJs will throw an error to the console letting you know.