<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/js-data/js-data-schema/master/dist/js-data-schema.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Open up your console to see the output</h1>
</body>
</html>
var schemator = new Schemator();
console.log('schemator.availableRules()', schemator.availableRules());
schemator.defineRule('divisibleBy', function(x, divisor) {
if (typeof x === 'number' && typeof divisor === 'number' && x % divisor !== 0) {
return {
rule: 'divisibleBy',
actual: '' + x + ' % ' + divisor + ' === ' + (x % divisor),
expected: '' + x + ' % ' + divisor + ' === 0'
};
}
return null;
});
console.log('schemator.availableRules()', schemator.availableRules());
console.log('schemator.defineSchema(\'mySchema\', { seats: { divisibleBy: 4 } })');
schemator.defineSchema('mySchema', {
seats: {
divisibleBy: 4
}
});
console.log('schemator.getSchema(\'mySchema\').validateSync({ seats: 16 })');
var errors = schemator.getSchema('mySchema').validateSync({
seats: 16
});
console.log('errors', errors);
console.log('schemator.getSchema(\'mySchema\').validateSync({ seats: 17 })');
errors = schemator.getSchema('mySchema').validateSync({
seats: 17
});
console.log('errors', errors);
console.log('schemator.defineRule(\'divisibleByAsync\', function (x, divisor, cb) {...}, true)');
schemator.defineRule('divisibleByAsync', function(x, divisor, cb) {
// asynchronity here is fake, but you could do something async, like make an http request
setTimeout(function() {
if (typeof x === 'number' && typeof divisor === 'number' && x % divisor !== 0) {
cb({
rule: 'divisibleBy',
actual: '' + x + ' % ' + divisor + ' === ' + (x % divisor),
expected: '' + x + ' % ' + divisor + ' === 0'
});
}
cb(null);
}, 1);
}, true); // pass true as the third argument
console.log('schemator.availableRules()', schemator.availableRules());
console.log('schemator.defineSchema(\'mySchema2\', { seats: { divisibleByAsync: 4 } })');
schemator.defineSchema('mySchema2', {
seats: {
divisibleByAsync: 4
}
});
console.log('schemator.getSchema(\'mySchema2\').validate({ seats: 16 }, function (errors) {...})');
schemator.getSchema('mySchema').validate({
seats: 16
}, function(errors) {
console.log('errors', errors);
console.log('schemator.getSchema(\'mySchema2\').validate({ seats: 17 }, function (errors) {...})');
schemator.getSchema('mySchema').validate({
seats: 17
}, function(errors) {
console.log('errors', errors);
});
});
## Schemator#defineRule(name, ruleFunc[, async])
Define a new rule.