Skip to content

Test Results

Charl Gottschalk edited this page Jul 20, 2016 · 7 revisions

All tests return a default object as a result, always containing at least two properties.

{
    approved: true|false,
    errors: []
}

result.approved will be true if the test passed and false if the test failed.

result.errors is an array containing any error messages if the test failed.

Some tests, such as the strength test, might return additional properties with the default result. Learn more from built in tests.

Accessing Errors

You can access errors returned by the result in one of two ways:

Errors Property
for (var i = result.errors.length - 1; i >= 0; i--) {
    console.log(result.errors[i]);
}
.each Method

The result object exposes an each() method for easily getting to errors.

result.each(function(error) {
    console.log(error);
});

Error Formatting

All default errors are automatically formatted to display correctly.

For instance, the range test's default error message is '{title} must be a minimum of {min} and a maximum of {max} characters'. As you can see, the message contains three placeholders, {title}, {min} and {max}. These placeholders are automatically replaced with the correct values when added to the result.

{min} will be replaced by the range test's min:? constraint, and {max} with the max:? constraint. {title} will be replaced with the title:? property in the rules object, or an empty string if the {title:?} property is absent.

Example

The rule, without the title:? property

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

var result = approve.value('Some text', rule);

will return the following result if the test fails

{
    approved: false,
    errors: [
        'must be a minimum of 5 and a maximum of 20 characters'
    ]
}

The error message is formatted to be 'must be a minimum of 5 and a maximum of 20 characters'.

If we include the title:? property

var rule = {
    title: 'Username',
    range: {
        min: 5,
        max: 20
    }
};

the result will now be

{
    approved: false,
    errors: [
        'Username must be a minimum of 5 and a maximum of 20 characters'
    ]
}

The error message now includes the title: 'Username must be a minimum of 5 and a maximum of 20 characters'.