Skip to content

Instantly share code, notes, and snippets.

@dead-horse
Created January 7, 2015 15:47
Show Gist options
  • Save dead-horse/a32a2eb2451f7d2b63d8 to your computer and use it in GitHub Desktop.
Save dead-horse/a32a2eb2451f7d2b63d8 to your computer and use it in GitHub Desktop.
var check = require('./');
var rule = {
name: 'string',
age: {type: 'int', max: 200},
gender: ['male', 'female'],
working: 'boolean',
salary: {type: 'number', min: 0},
birthday: 'date',
now: 'dateTime',
id: 'id',
childrens: {
type: 'array',
required: false,
rule: {
name: 'string',
age: 'int',
gender: ['male', 'female'],
birthday: {type: 'date', required: false}
}
},
mate: {
type: 'object',
required: false,
rule: {
name: 'string',
age: 'int',
gender: ['male', 'female'],
birthday: {type: 'date', required: false}
}
}
};
var valid = {
name: 'foo',
gender: 'male',
age: 30,
working: true,
salary: 10000.1,
birthday: '1990-01-01',
now: '2015-01-07 00:00:00',
id: '052111',
childrens: [{
name: 'bar1',
age: 1,
gender: 'female',
birthday: '2014-01-01'
}, {
name: 'bar2',
age: 2,
gender: 'male',
birthday: '2013-01-01'
}],
mate: {
name: 'hee',
age: 29,
gender: 'female'
}
};
var invalid = {
name: 1,
gender: 'male1',
age: 300,
working: 'true',
salary: '10000.1',
birthday: '1990-01-011',
id: '052111x',
childrens: [{
name: 'bar1',
gender: 'female',
birthday: '2014-01-01'
}, {
name: 'bar2',
age: 2,
birthday: '2013-01-01'
}],
mate: {
age: 29,
gender: 'female'
}
};
console.log('valid object result: ', check(valid, rule));
console.log('invalid object result: ', check(invalid, rule));
// valid object result: undefined
// invalid object result: [ { message: 'name should be a string',
// code: 'invalid',
// field: 'name' },
// { message: 'age should smaller than 200',
// code: 'invalid',
// field: 'age' },
// { message: 'gender should be one of male, female',
// code: 'invalid',
// field: 'gender' },
// { message: 'working should be a boolean',
// code: 'invalid',
// field: 'working' },
// { message: 'salary should be a number',
// code: 'invalid',
// field: 'salary' },
// { message: 'birthday should match /^\\d{4}\\-\\d{2}\\-\\d{2}$/',
// code: 'invalid',
// field: 'birthday' },
// { message: 'now required', field: 'now', code: 'missing_field' },
// { message: 'id should match /^\\d+$/',
// code: 'invalid',
// field: 'id' },
// { message: 'childrens[0].age',
// field: 'childrens[0].age',
// code: 'missing_field' },
// { message: 'childrens[1].gender',
// field: 'childrens[1].gender',
// code: 'missing_field' },
// { message: 'mate.name',
// field: 'mate.name',
// code: 'missing_field' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment