Skip to content

Instantly share code, notes, and snippets.

@Kami
Created May 27, 2012 07:49
Show Gist options
  • Select an option

  • Save Kami/2802676 to your computer and use it in GitHub Desktop.

Select an option

Save Kami/2802676 to your computer and use it in GitHub Desktop.
Swiz - validation example
var swiz = require('swiz');
var Valve = swiz.Valve;
var Chain = swiz.Chain;
var O = swiz.struct.Obj;
var F = swiz.struct.Field;
var defs = [
O('Server',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the server', 'attribute': true,
'val' : Chain().isString()}),
F('is_active', {'src': 'active', 'desc': 'is the server active?',
'val' : Chain().toBoolean(), 'coerceTo' : 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true,
'val' : Chain().isString()}),
F('agent_name', {'val' : Chain().isString().notEmpty()}),
F('ipaddress' , {'src' : 'get_public_address', 'val' : Chain().isIP()})
],
'plural': 'servers'
})
];
var validity = swiz.defToValve(defs), v = new Valve(validity.Server);
// Valid payload
var goodServer = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'example',
'agent_name' : 'my server #1',
'ipaddress' : '42.24.42.24'
};
v.check(goodServer, function(err, cleaned) {
console.log('Success:');
console.log(cleaned);
});
// Invalid payload
var badServer = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'example',
'agent_name' : 'my server #1',
'ipaddress' : '127.0'
};
v.check(badServer, function(err, cleaned) {
console.log('Error - invalid ip:');
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment