Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

simplify error objects

  • Loading branch information...
commit 0ed2a63441561a3927f21254a188647f1e37816d 1 parent b3df86d
Scott Bronson authored
Showing with 49 additions and 46 deletions.
  1. +12 −11 README.md
  2. +8 −6 lib/valid.js
  3. +29 −29 test/validjson.test.js
23 README.md
View
@@ -11,12 +11,12 @@ A lightweight, chaining validation library.
```javascript
var Valid = require('valid');
var inRange = Valid.number().min(4).max(9)
- inRange.check(3) // check returns true/false, here it returns false
- inRange.test(12) // returns "is not less than or equal to 9"
+ inRange.check(7) // returns nothing -- no errors
+ inRange.check('7') // returns "must be a number"
+ inRange.check(12) // returns "must be less than or equal to 9"
Valid.optional().string().check(null); // can be null, undefined, or a string
- Valid.array(Valid.integer).check([1,2,3]); // checks each item in the array
- var isHex = Valid.match(/^[0-9A-F]$/i).message("should be a hexadecimal number");
+ Valid.array(Valid.integer()).check([1,2,3]); // checks each item in the array
// test JSON structures:
var Schema = {
@@ -46,7 +46,6 @@ A lightweight, chaining validation library.
This library is scary new.
-- simplify error objects
- try to shrink the api, implement kitchen-sink
- npm publish
- pass a json schema to array()? factor into RunSubtest & have everything call this.
@@ -62,8 +61,8 @@ This library is scary new.
# Introduction
-Valid allows you to declare a validation and then test it against
-any number of values:
+Valid allows you to declare a validation and run it against any number of
+values:
```javascript
var validation = Valid.integer().even().min(6);
@@ -114,13 +113,15 @@ It's easy to supply your own error messages:
Valid.match(/-/).message("must contain a dash")
Because JSON validations need to return multiple errors, they return an object
-instead of a string. The `value` field contains the value that failed to
-validate.
+instead of a string. The error object has the same structure as the JSON
+except that arrays are converted into objects.
```javascript
{
- "Name" : { message: "is blank", value: "" },
- "Addresses[0].State" : { message: "doesn't match /[A-Z][A-Z]/", value: "ca" }
+ Name: "is blank",
+ Address: {
+ State: "doesn't match /[A-Z][A-Z]/"
+ }
}
```
14 lib/valid.js
View
@@ -248,14 +248,16 @@ Valid.max = Valid.le;
// JSON Schema
Valid.JsonError = function(path, value, message) {
- var str = '';
- for(var i=0; i<path.length; i++) {
- str += Valid.integer().isValid(path[i]) ? '['+path[i]+']' : (str === '' ? '' : '.') + path[i];
+ var error = this._errors;
+ var last = path.length - 1;
+ var key = path.length === 0 ? '.' : path[last];
+
+ for(var i=0; i<last; i++) {
+ if(!error[path[i]]) error[path[i]] = {};
+ error = error[path[i]];
}
- if(str === '') str = '.';
- if(this._errors[str]) return; // ignore duplicate errors
- this._errors[str] = {value: value, message: message};
+ error[key] = message;
this._errorCount += 1;
};
58 test/validjson.test.js
View
@@ -64,7 +64,7 @@ if(false) Valid.json(PersonSchema).assert({ // now validate this JSON
// first test the validation routines
if(Valid.json({a:1}).check({a:1}) !== undefined) throw Error("test() success must return undefined");
-var result = DeepCompare(Valid.json({a:1}).check({a:2}), {'a': {value: 2, message: 'must equal 1'}});
+var result = DeepCompare(Valid.json({a:1}).check({a:2}), {'a': 'must equal 1'});
if(result) throw Error("test() failure was wrong: " + result);
if(Valid.json({a:1}).isValid({a:1}) !== true) throw Error("check() success must return true");
if(Valid.json({a:1}).isValid({a:2}) !== false) throw Error("check() failure must return false");
@@ -73,61 +73,61 @@ if(Valid.json({a:1}).isValid({a:2}) !== false) throw Error("check() failure
// now ensure Valid.json works
Valid.json(true ).assert(true);
Valid.json(false).assert(false);
-Valid.json(true ).assert(false, {'.': {message: "must equal true", value: false}});
-Valid.json(false).assert(true, {'.': {message: "must equal false", value: true}});
-Valid.json(false).assert(undefined, {'.': {message: "must equal false", value: undefined}});
+Valid.json(true ).assert(false, {'.': "must equal true"});
+Valid.json(false).assert(true, {'.': "must equal false"});
+Valid.json(false).assert(undefined, {'.': "must equal false"});
Valid.json(null).assert(null);
-Valid.json(null).assert(undefined, {'.': {message: "must be null", value: undefined}});
+Valid.json(null).assert(undefined, {'.': "must be null"});
Valid.json(undefined).assert(undefined);
-Valid.json(undefined).assert(null, {".": {message: "must equal undefined", value:null}});
-Valid.json(null).assert({}, {".": {message: "must be null", value: {}}});
-Valid.json({}).assert(null, {".": {message: "can't be null", value: null}});
+Valid.json(undefined).assert(null, {".": "must equal undefined"});
+Valid.json(null).assert({}, {".": "must be null"});
+Valid.json({}).assert(null, {".": "can't be null"});
Valid.json('abc' ).assert('abc');
-Valid.json('abc' ).assert('abc ', {'.': {message: "must equal 'abc'", value: "abc "}});
+Valid.json('abc' ).assert('abc ', {'.': "must equal 'abc'"});
Valid.json(123 ).assert(123);
-Valid.json(123 ).assert(123.1, {'.': {message: "must equal 123", value: 123.1}});
+Valid.json(123 ).assert(123.1, {'.': "must equal 123"});
Valid.json(/^abc$/).assert('abc');
-Valid.json(/^abc$/).assert('abcd', {'.': {message: "must match /^abc$/", value: 'abcd'}});
+Valid.json(/^abc$/).assert('abcd', {'.': "must match /^abc$/"});
Valid.json(/abc/ ).assert('In abc.');
Valid.json(/abc/i ).assert('DEABCDEF');
-Valid.json(/abc/ ).assert('DEABCDEF', {".": {message:"must match /abc/", value:"DEABCDEF"}});
+Valid.json(/abc/ ).assert('DEABCDEF', {".": "must match /abc/"});
Valid.json({abc: 123} ).assert({abc: 123});
-Valid.json({abc: 123, def: 456}).assert({abc: 123}, {'.': {message: "must include def", value: {"abc":123}}});
-Valid.json({abc: 123} ).assert({abc: 123, def: 456}, {'.': {message: "can't include def", value: {"abc":123,"def":456}}});
-Valid.json({abc: 123} ).assert({}, {".":{message: "must include abc", value: {}}});
-Valid.json({} ).assert({abc: 123}, {".":{message: "can't include abc", value: {"abc":123}}});
+Valid.json({abc: 123, def: 456}).assert({abc: 123}, {'.': "must include def"});
+Valid.json({abc: 123} ).assert({abc: 123, def: 456}, {'.': "can't include def"});
+Valid.json({abc: 123} ).assert({}, {".":"must include abc"});
+Valid.json({} ).assert({abc: 123}, {".":"can't include abc"});
-Valid.json({a: {b: {c: 1}}}).assert({a: {b: {c: 2}}}, {'a.b.c': {message: "must equal 1", value: 2}});
+Valid.json({a: {b: {c: 1}}}).assert({a: {b: {c: 2}}}, {'a':{'b':{'c': "must equal 1"}}});
Valid.json({a: {b: /wut/i}}).assert({a: {b: "NOWUTY"}});
-Valid.json({a:{}}).assert({a:1}, {"a":{"value":1,"message":"must be an object"}});
-Valid.json({a:1,b:{c:{d:2}}}).assert({a:1,b:{c:1}}, {"b.c":{"value":1,"message":"must be an object"}});
+Valid.json({a:{}}).assert({a:1}, {"a":"must be an object"});
+Valid.json({a:1,b:{c:{d:2}}}).assert({a:1,b:{c:1}}, {'b':{'c':"must be an object"}});
// Valid chains
Valid.json(Valid.optional().string()).assert(undefined);
Valid.json(Valid.optional().string()).assert(null);
Valid.json(Valid.optional().string()).assert("5544");
-Valid.json(Valid.optional().string()).assert(6655, {'.': {message: 'must be a string', value: 6655} });
+Valid.json(Valid.optional().string()).assert(6655, {'.': 'must be a string'});
// functions
Valid.json(function(val) {}).assert(12);
-Valid.json(function(val) { return "value is " + val; }).assert(12, {'.': {message: 'value is 12', value: 12} });
+Valid.json(function(val) { return "value is " + val; }).assert(12, {'.': 'value is 12'});
// arrays
Valid.json([12, 13]).assert([12, 13]);
-Valid.json([12, 13]).assert([12, 14], {"[1]": {message: "must equal 13", value: 14}});
-Valid.json([12, 13]).assert(12, {".": {message:"must be an array", value: 12}});
-Valid.json([12, 13]).assert(undefined, {".": {message: "must be an array", value: undefined}});
-Valid.json([12, 13]).assert(null, {".": {message: "can't be null", value: null}});
+Valid.json([12, 13]).assert([12, 14], {"1": "must equal 13"});
+Valid.json([12, 13]).assert(12, {".": "must be an array"});
+Valid.json([12, 13]).assert(undefined, {".": "must be an array"});
+Valid.json([12, 13]).assert(null, {".": "can't be null"});
Valid.json(Valid.array() ).assert([]);
Valid.json(Valid.array() ).assert([1,2,3]);
Valid.json(Valid.array(Valid.integer())).assert([1,2,3]);
-Valid.json(Valid.array(Valid.integer())).assert([1,2,'3'], {".": {message: "item 2 must be an integer", value: [1,2,"3"]}});
-Valid.json(Valid.array() ).assert({"1":"2"}, {".": {message: "must be an array", value: {"1":"2"}}});
-Valid.json(Valid.array() ).assert(null, {".": {message: "must be an array", value: null}});
+Valid.json(Valid.array(Valid.integer())).assert([1,2,'3'], {".": "item 2 must be an integer"});
+Valid.json(Valid.array() ).assert({"1":"2"}, {".": "must be an array"});
+Valid.json(Valid.array() ).assert(null, {".": "must be an array"});
Valid.json([12, Valid.integer()]).assert([12, 13]);
-Valid.json([12, Valid.integer()]).assert([12, "13"], {"[1]": {message: "must be an integer", value: "13"}});
+Valid.json([12, Valid.integer()]).assert([12, "13"], {"1": "must be an integer"});
Please sign in to comment.
Something went wrong with that request. Please try again.