Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

API cleanup: check() -> isValid(), test() -> check()

  • Loading branch information...
commit 99bddac9c23cc61ab79a91fcb3e2eae2a0cefadb 1 parent a23d266
@bronson authored
View
29 README.md
@@ -14,13 +14,13 @@ A lightweight, chaining validation library.
inRange.check(3) // check returns true/false, here it returns false
inRange.test(12) // returns "is not less than or equal to 9"
- Valid.optional().string() // success is null, undefined, or a string
+ 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 Schema = {
Name: Valid.notBlank(),
- Numbers: Valid.array(Valid.integer()).len(2,5), // an array of 2, 3, 4, or 5 integers
Address: {
- State: /^[A-Z][A-Z]$/, // shortcut for Valid.match(/^[A-Z][A-Z]$/)
+ State: /^[A-Z][A-Z]$/, // shortcut for Valid.match(/^[A-Z][A-Z]$/)
Country: "US"
}
};
@@ -51,20 +51,15 @@ This library is scary new.
# Introduction
-Valid allows you to declare strings of validations and
-use them to test different values:
+Valid allows you to declare a validation and then test it against
+any number of values:
```javascript
- var checker = Valid.integer().even().min(6);
- checker.test(9); // returns "9 is not even"
- checker.check(10); // returns true
+ var validation = Valid.integer().even().min(6);
+ validation.check(9); // returns "9 is not even"
+ validation.isValid(10); // returns true.
```
-Valid offers three ways of testing values:
-
-- test(val) -- returns undefined on success or the error if the validation failed.
-- check(val) -- returns true or false.
-
The error will be a string for simple validations or an object
for JSON validations (see _Errors_ below).
@@ -85,9 +80,10 @@ See [valid.js](https://github.com/bronson/valid/blob/master/lib/valid.js).
- Utilities: nop(), fail([message]), messageFor(test,message), todo([test])
- JSON: json(schema)
-\*: These are JavaScript keywords. While `Valid.undefined()` will work
-with a lot of interpreters, it won't work everywhere.
-Each keyword validation has a more compatible alternative: Valid.undef(), Valid.nil(), etc.
+\*: These are JavaScript keywords. While `Valid.undefined()` works
+with a lot of interpreters, it doesn't work everywhere.
+Each keyword validation has a more compatible alternative that should
+be used instead: Valid.undef(), Valid.nil(), etc.
# Errors
@@ -107,7 +103,6 @@ the value that failed to validate.
}
```
-
# Extending Valid
To define your own validations, just end the chain with "define()"
View
36 lib/valid.js
@@ -27,11 +27,11 @@ Valid.GetChain = function GetChain() {
// Adds the given validation to the current Chain.
// Data is optional but can help identify the validation when debugging.
-Valid.AddValidation = function AddValidation(test, data) {
+Valid.AddValidation = function AddValidation(validation, data) {
var self = this.GetChain();
if(self._queue === undefined) self._queue = [];
- if(data) test.data = data;
- self._queue.push(test);
+ if(data) validation.data = data;
+ self._queue.push(validation);
return self;
};
@@ -66,7 +66,7 @@ Valid.Escape = function Escape(value) {
// Turns a Chain object into a callable Validation.
// Valid.isFour = Valid.equal(4).define(); // define the isFour validation
-// Valid.integer().isFour().test(4); // success!
+// Valid.integer().isFour().isValid(4); // true!
// If you get this error then you forgot to call define() on your chain:
// Property 'myfunc' of object function Valid() { } is not a function
// It's really shameful that this function needs to exist.
@@ -95,14 +95,14 @@ Valid.define = function define() {
// results
// returns the error string or undefined if there were no validation errors
-Valid.test = function test(value) {
+Valid.check = function check(value) {
var self = this.GetChain();
return self.GetChain().ValidateQueue(self._queue, value);
};
// returns true if the validation succeeded, false if there were errors
-Valid.check = function check(value) {
- return !this.test(value);
+Valid.isValid = function isValid(value) {
+ return !this.check(value);
};
@@ -138,11 +138,11 @@ Valid.type = Valid.SimpleValidation(function Type(value,type) {
if(typeof value !== type) return "is of type " + (typeof value) + " not " + type;
});
-Valid.array = Valid.SimpleValidation(function Arry(value, test) {
+Valid.array = Valid.SimpleValidation(function Arry(value, validation) {
if(!Array.isArray(value)) return "is not an array";
- if(test !== undefined) {
+ if(validation !== undefined) {
for(var i=0; i<value.length; i++) {
- var error = this.ValidateQueue(test._queue, value[i]);
+ var error = this.ValidateQueue(validation._queue, value[i]);
if(error) return "item " + i + " " + error;
}
}
@@ -158,14 +158,14 @@ Valid.len = Valid.SimpleValidation(function Len(value,min,max) {
}
});
-Valid.messageFor = Valid.SimpleValidation(function Msg(value, test, message) {
- var error = this.ValidateQueue(test._queue, value);
+Valid.messageFor = Valid.SimpleValidation(function Msg(value, validation, message) {
+ var error = this.ValidateQueue(validation._queue, value);
if(error) return message;
});
-Valid.not = Valid.SimpleValidation(function Not(value, test, message) {
- var error = this.ValidateQueue(test._queue, value);
- if(!error) return message || "test should have failed";
+Valid.not = Valid.SimpleValidation(function Not(value, validation, message) {
+ var error = this.ValidateQueue(validation._queue, value);
+ if(!error) return message || "validation should have failed";
});
// seems somewhat useless since V.a().b() is the same as V.and(V.a(),V.b())
@@ -250,7 +250,7 @@ Valid.max = Valid.le;
Valid.JsonError = function(path, value, message) {
var str = '';
for(var i=0; i<path.length; i++) {
- str += Valid.integer().check(path[i]) ? '['+path[i]+']' : (str === '' ? '' : '.') + path[i];
+ str += Valid.integer().isValid(path[i]) ? '['+path[i]+']' : (str === '' ? '' : '.') + path[i];
}
if(str === '') str = '.';
@@ -290,7 +290,7 @@ Valid.JsonField = function(path, value, schema) {
case 'function':
if(schema instanceof RegExp) {
- var reresult = Valid.match(schema).test(value);
+ var reresult = Valid.match(schema).check(value);
if(reresult) this.JsonError(path, value, reresult);
} else {
var fresult = schema.call(this, value);
@@ -303,7 +303,7 @@ Valid.JsonField = function(path, value, schema) {
if(schema === null) {
if(value !== null) this.JsonError(path, value, "is not null");
} else if(schema._queue && typeof schema.GetChain === 'function') { // try to detect a Valid chain
- var vresult = schema.test(value);
+ var vresult = schema.check(value);
if(vresult) this.JsonError(path, value, vresult);
} else if(value === null) {
this.JsonError(path, value, "is null");
View
12 test/valid.test.js
@@ -7,7 +7,7 @@ var Valid = require('../lib/valid');
// throws an error if the result doesn't exactly match the expectation
Valid.assert = function assert(value, expected) {
- var actual = this.test(value);
+ var actual = this.check(value);
if(expected !== actual) {
var exstr = (expected === undefined ? "success" : "'" + expected + "'");
var acstr = (actual === undefined ? "success" : "'" + actual + "'");
@@ -17,10 +17,10 @@ Valid.assert = function assert(value, expected) {
// first test the validation routines
-if(Valid.equal(4).test(4) !== undefined) throw "test() success needs to return undefined";
-if(Valid.equal(4).test(5) !== "is not equal to 4") throw "test() failure needs to return a string";
-if(Valid.equal(4).check(4) !== true) throw "check() success needs to return true";
-if(Valid.equal(4).check(5) !== false) throw "check() failure needs to return false";
+if(Valid.equal(4).check(4) !== undefined) throw "test() success needs to return undefined";
+if(Valid.equal(4).check(5) !== "is not equal to 4") throw "test() failure needs to return a string";
+if(Valid.equal(4).isValid(4) !== true) throw "check() success needs to return true";
+if(Valid.equal(4).isValid(5) !== false) throw "check() failure needs to return false";
// pathological cases
@@ -185,7 +185,7 @@ Valid.or( Valid.nil(), Valid.undef() ).assert(null);
Valid.or( Valid.nil(), Valid.number(), Valid.string() ).assert('mosdef');
Valid.or( Valid.undef(), Valid.match(/^abc$/), Valid.match(/def$/) ).assert('mosdef');
Valid.or( Valid.type('number'), Valid.match(/^bbc$/) ).assert('abc', "is of type string not number and does not match /^bbc$/");
-Valid.not( Valid.nil() ).assert(null, "test should have failed");
+Valid.not( Valid.nil() ).assert(null, "validation should have failed");
Valid.not( Valid.nil() ).assert(undefined);
Valid.not( Valid.equal(4), "equalled 4" ).assert(4, "equalled 4");
View
14 test/validjson.test.js
@@ -9,7 +9,7 @@ var DeepCompare = require('./deepcompare');
// throws an error unless the result exactly matches what is expected
Valid.assert = function assert(value, expected) {
- var actual = this.test(value);
+ var actual = this.check(value);
var diffstr = DeepCompare(expected, actual);
if(diffstr) {
var exstr = (expected === undefined ? "success" : JSON.stringify(expected));
@@ -23,7 +23,7 @@ Valid.assert = function assert(value, expected) {
// quick real-world scenario...
var AddressSchema = { // schema for an address
- Address : Valid.array(Valid.string()).len(1,2),
+ Address : Valid.or(Valid.notBlank(), Valid.array(Valid.notBlank()).len(1,2)),
CityName : Valid.notBlank(),
StateName : /^[A-Z][A-Z]$/, // or Valid.oneOf({AR:true,AZ:true,...})
PostalCode : /^[0-9]{5}(-[0-9]{4})?/,
@@ -46,7 +46,7 @@ if(false) Valid.json(PersonSchema).assert({ // now validate this JSON
MiddleName : null,
LastName : 'Bronson',
HomeAddress : {
- Address : ["123 Easy St."],
+ Address : "123 Easy St.",
CityName : "Santa Cruz",
StateName : "CA",
PostalCode : "95063-1337",
@@ -63,11 +63,11 @@ if(false) Valid.json(PersonSchema).assert({ // now validate this JSON
// first test the validation routines
-if(Valid.json({a:1}).test({a:1}) !== undefined) throw "test() success needs to return undefined";
-var result = DeepCompare(Valid.json({a:1}).test({a:2}), {'a': {value: 2, message: 'does not equal 1'}});
+if(Valid.json({a:1}).check({a:1}) !== undefined) throw "test() success needs to return undefined";
+var result = DeepCompare(Valid.json({a:1}).check({a:2}), {'a': {value: 2, message: 'does not equal 1'}});
if(result) throw "test() failure was wrong: " + result;
-if(Valid.json({a:1}).check({a:1}) !== true) throw "check() success needs to return true";
-if(Valid.json({a:1}).check({a:2}) !== false) throw "check() failure needs to return false";
+if(Valid.json({a:1}).isValid({a:1}) !== true) throw "check() success needs to return true";
+if(Valid.json({a:1}).isValid({a:2}) !== false) throw "check() failure needs to return false";
// now ensure Valid.json works
Please sign in to comment.
Something went wrong with that request. Please try again.