validation-result
Wrapper for unified client-server and function-function communication with methods to simplify validation and error handling.
{ // Wrapped data thisdata = data; // Validity flag thisisValid; // Lists of messages thiserrors = ; thiswarnings = ; thismessages = ; // ...validation functions...}
Installation
npm install validation-result
Usage
Include validation-result in your file:
var ValidationResult = ;
Then use it to wrap any object
var validation = data;
Basic functions and properties
// Check if data are validif !validationisValid // Data are not valid // Add error to list of errors// sets isValid to falsevalidation; // Add message to message listvalidation; // Add warning to warnings listvalidation; // Append other validationsif !validation // Data are not valid
Validation functions
Each validation function returns its result. If the result is false, validation.addError(error)
is called.
// Check if given property is numbervalidation); // Check if given property is lesser or equal than given valuevalidation); // Check if given property is greater or equal than given valuevalidation); // Check if given property is equal to given valuevalidation); // Check if given expression is truevalidation; // Check if given property is not emptyvalidation); // Check if given property is definedvalidation); // Check if given property matches given regexvalidation); // Check if given property contains given valuevalidation);
Example
// Require modulevar ValidationResult = ; // Create example datavar user = Name: "Bob" Age: 17 Local: Password: "ucantgetme" // Wrap user in validationvar validation = user; // Make validation controlsvalidation;validation;validation; // Does it make sense to keep going?if !validationisValid return validation; // Nested validation to avoid access to undefined properties// If we do not want to append error message, dontif validation validation; // Use your own checksif myMoodIsBlue validation; // Return validationreturn validation;
Testing
npm test