Skip to content

v0.5.0

Compare
Choose a tag to compare
@icebob icebob released this 03 Jul 12:11
· 688 commits to master since this release

Multiple validators

There is possible to define more validators for a field. In this case if one of all validators is success, the field will be valid.

let schema = {
    cache: [
        { type: "string" },
        { type: "boolean" }
    ]
}

v.validate({ cache: true }, schema); // Valid
v.validate({ cache: "redis://" }, schema); // Valid
v.validate({ cache: 150 }, schema); // Fail

Custom validator

You can also create your custom validator.

let v = new Validator({
    messages: {
        // Register our new error message text
        evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
    }
});

// Register a custom 'even' validator
v.add("even", value => {
    if (value % 2 != 0)
        return v.makeError("evenNumber", null, value);

    return true;
});

const schema = {
    name: { type: "string", min: 3, max: 255 },
    age: { type: "even" }
};

console.log(v.validate({ name: "John", age: 20 }, schema));
// Returns: true

console.log(v.validate({ name: "John", age: 19 }, schema));
/* Returns an array with errors:
    [{
        type: 'evenNumber',
        expected: null,
        actual: 19,
        field: 'age',
        message: 'The \'age\' field must be an even number! Actual: 19'
    }]
*/

Or you can use the custom type with inline checker function:

let v = new Validator({
	messages: {
		// Register our new error message text
		weightMin: "The weight must be larger than {expected}! Actual: {actual}"
	}
});

const schema = {
	name: { type: "string", min: 3, max: 255 },
	weight: { 
		type: "custom", 
		minWeight: 10, 
		check(value, schema) {
			return (value < schema.minWeight)
				? this.makeError("weightMin", schema.minWeight, value)
				: true;
		}
	}
};

console.log(v.validate({ name: "John", weight: 50 }, schema));
// Returns: true

console.log(v.validate({ name: "John", weight: 8 }, schema));
/* Returns an array with errors:
	[{ 
		type: 'weightMin',                                       
		expected: 10,                                            
		actual: 8,                                               
		field: 'weight',                                         
		message: 'The weight must be larger than 10! Actual: 8' 
	}]
*/