There are lots of form validation libraries and jQuery plugins. Though I cannot find a code contract library, for validating function arguments.
As an example, to do contract validation in .NET, you could use the outstanding Conditions library. I'm looking for something similar for JavaScript. The closest I can find is Speks, but its for Node.js and is geared for testing, whereas I need to bake the validation into release code.
Examples of validation methods I need: checks for null, empty, isstring, isnumber, length, min, max, value, less than, greater than, between, not equal, not less than, not greater than, etc.
This is a runtime type contracts library which takes on some Haskell like syntax: http://code.google.com/p/ristretto-js.
I was pretty impressed by the implementation put together for this question:
JavaScript Code Contract Libraries?
Example:
function syncTime(serverTime, now) {
Verify.value(serverTime).always().isDate(); // Cannot be undefined or null.
Verify.value(now).whenDefined().isDate(); // Cannot be null, but must be date when defined.
//Code
}
Why not just roll a library yourself?
Using a strategy pattern, you can easily run a series of methods on a specific value.
Here is a semi-crude example. This obviously needs more error handling and modification, but it provides an idea for what you could build. http://jsfiddle.net/fBfgz/
var validator = (function() {
// Available checks
var types = {
isNum: function(value) {
return !isNaN(value);
},
isNull: function(value) {
return value === null;
}
};
return {
validate: function (data) {
var i, len, check, ret;
for (i = 0, len = data.checks.length; i < len; i += 1) {
if (types.hasOwnProperty(data.checks[i])) {
check = types[data.checks[i]];
ret = check(data.value);
alert(ret);
if (!ret) {
return false;
}
}
}
return true;
}
};
}());
validator.validate({ // will return true
value: 32,
checks: ['isNum']
});
validator.validate({ // will return false
value: 32+'a',
checks: ['isNum']
});
I would probably use QUnit for general purpose javascript testing. Also check out Tim Disney's contracts.js, which may be more specific to your use case.
Sweet-contracts does exactly what you want.
Sweet-contracts is a module requiring sweet.js, and uses macros to add contracts right into the language. This way you don't have to hack your contracts using existing (and usually insufficient/inefficient) language constructs.
sweet.js allows you to create macros that can expand the language modularly. This blog post gives a great introduction to sweet and the power of macros. You can try it out live in your browser at this address.
来源:https://stackoverflow.com/questions/8597665/is-there-a-code-contract-library-for-javascript