Warning This repo is deprecated. Please see the fjl monorepo for the latest sources.
Functional validator(s) implementation (inspired by Zend/Validator validators).
- Requirements
- Getting Started
- Docs
- Motivation
- Development
- Supported Platforms
- License
- Resources
- Change log
- Javascript Ecmascript 5+.
- IE9+, and all other modern day browsers.
- 8+
fjl-validator
was'nt meant to be used alone though what a user will most likely want is
fjl-input-filter
though below is a standalone hypothetical scenario:
// Let's say this is somewhere on the server:
import {regexValidator, stringLengthValidator, toValidationResult} from 'fjl-validator';
const nameFieldValidators = [
stringLengthValidator({min: 3, max: 55}),
regexValidator({
pattern: /^[a-z][a-z"'.\s]*$/i,
messageTemplates: {
DOES_NOT_MATCH_PATTERN:
`Only letters, spaces, quotes (""", "'"), and periods are allowed for names.`
}
})
],
runValidators = (validators, breakOnFailure, value) => {
let result = true,
i = 0,
messageResults = [];
if (!validators || !validators.length) {
return toValidationResult({result});
}
const limit = validators.length;
for (; i < limit; i++) {
const vResult = validators[i](value);
if (!vResult.result) {
messageResults.push(vResult.messages);
result = false;
if (breakOnFailure) {
break;
}
}
}
return toValidationResult({result, messages: [].concat(...messageResults)});
},
nameFieldValue = '', // Extract/receive name field value here
validationResult = runValidators(nameFieldValidators, false, nameFieldValue;
// Elsewhere (let's say, hypothetically in a react view)
import React, {Component} from 'react';
import {uuid} from './your-utils';
class SomeReactFormComponent extends Component {
// ...
render () {
const {validationResult} = this.state;
return (<div className="form-field">
// ...
// If validation result is `true` don't render anything, else render error messages
{validationResult.result ? null :
(<ul>{validationResult.messages.map(message => (<li key={uuid()}>{message}</li>))}</ul>)
// ...
</div>);
}
// ...
}
import {...} from 'fjl-validator';
const {...} = require('fjl-validator');
See desired export type below:
- './dist/amd/' - Asynchronous module format.
- './dist/cjs/' - CommonJs module format.
- './dist/umd/' - Universal module definition format.
- './dist/iife/' - Immediately Invoked Function Execution - (exports
fjl
as a global). - './dist/es6-module/' - Ecmascript 6 module format.
JSDocs are here (https://functional-jslib.github.io/fjl-validator/) [https://functional-jslib.github.io/fjl-validator/].
alnumValidator, alnumValidator1, default
digitValidator, digitValidator1, default
toLengthOptions, lengthValidatorNoNormalize, lengthValidator, default
toNotEmptyOptions, notEmptyValidatorNoNormalize, notEmptyValidator,
notEmptyValidator1, default
toRegexValidatorOptions, regexValidatorNoNormalize, regexValidator,
default
toStringLengthOptions, stringLengthValidatorNoNormalize,
stringLengthValidator, default
defaultValueObscurator, getErrorMsgByKey, toValidationOptions,
toValidationResult, isOneOf, default
All methods that take more than one named param (take two or more arguments) are curried: I.e.,
alnumValidator, digitValidator, notEmptyValidator,
regexValidator, stringLengthValidator, getErrorMsgByKey, // et. al.
- Explicit one arg variadic methods (
(...args) => (...)
) are not curried:
toValidationResult, toValidationOptions
- The docs below only outline the default exports, and the pertinent methods required for rolling up your
own validation functions, from the sources in lib (except for 'ValidationUtils` file).
To see what other methods are exported in lib you can read the in-depth docs at https://functional-jslib.github.io/fjl-validator/ .
Returns valid validation options objects that can be used as validator options;
options {Object}
valueObscured {Boolean}
valueObscurator {Function.<String>}
- Obscurator function; E.g.x => "..."
messageTemplates {Object.<String, (MessageTemplateCallback|Function|String)>}
- Key value pairs of error messages or error message callbacks ( See virtual typeMessageTemplateCallback
@todo here).
{ValidationOptions}
- A strictly typed options object; Merges passed in options onto strictly typed version which
will throw clear error message(s) if type(s) for properties do not match.
Returns a valid validation result object;
options {Object}
result {Boolean}
- Result of validation (true || false
etc.).messages {Array.<String>}
- Error messages if any.[value {*}]
- Optionally, value that was passed in for validation.
{ValidationResult}
-
A strictly typed validation result object; Merges passed in options onto strictly typed version which
will throw clear error message(s) if type(s) do not match.
Validates values using a regular expression.
options {Object}
- Inherits all properties from
{ValidationOptions}
type ({valueObscurator, valueObscured, messageTemplates}
). pattern {RegExp}
messageTemplates {Object}
DOES_NOT_MATCH_PATTERN
- Key onmessageTemplates
to populate for custom 'does-not-match-pattern' message.
- Inherits all properties from
value {*}
- Value to validate.
{ValidationResult}
Alpha-numeric value validator.
options {Object}
- Same asregexValidator
's options.value {*}
regexValidator
{ValidationResult}
Same as alnumValidator
except doesn't require an options object.
value {*}
{ValidationResult}
Validates digits.
regexValidator
options {Object}
- Same asregexValidator
's options.value {*}
- Value to validate.
{ValidationResult}
Validates that a value is not an empty; I.e., Checks that value is not one of
[[], '', null, undefined, {}, Map(), Set(), WeakSet(), WeakMap()]
We'll refer to this set as Empty
here.
options {Object}
- Inherits all properties from
{ValidationOptions}
type ({valueObscurator, valueObscured, messageTemplates}
) also. messageTemplates
EMPTY_NOT_ALLOWED
- Key that can be populated for custom message on receiving anEmpty
(in virtual types).
- Inherits all properties from
value {*}
- Value to validate.
{ValidationResult}
Same as notEmptyValidator
except ignores first parameter.
value {*}
- Value to validate.
{ValidationResult}
Validates a lengthable items length.
options {Object}
min {Number}
- Default0
.max {Number}
- DefaultNumber.MAX_SAFE_INTEGER
messageTemplates {Object}
NOT_OF_TYPE {String|Function}
- Key for generating 'not of type' error.NOT_WITHIN_RANGE {String|Function}
- Key for generating 'not within range' error.
value {*}
- Value to validate.
{ValidationResult}
Validates a string's length.
options {Object}
min {Number}
- Default0
.max {Number}
- DefaultNumber.MAX_SAFE_INTEGER
messageTemplates {Object}
-NOT_OF_TYPE {String|Function}
- Key for generating 'not of type' error. -NOT_WITHIN_RANGE {String|Function}
- Key for generating 'not within range' error.
value {*}
- Value to validate.
{ValidationResult}
One of [null, undefined, '', 0, false, [], {}, Map(), Set(), WeakMap(), WeakSet()]
.
valueObscured {Boolean}
- Whether to obscure value in validation error messages when value doesn't pass validation. Defaultfalse
.valueObscurator {Function}
- Function that takes the value and returns an obscured version; E.g.,
const obscurator = x => Array.fill('*', 0, (x + '').length).join('');
obscure('hello') === '*****' // equals `true`
messageTemplates {Object}
- Key-value pair hash where the values should be either strings and/or functions in the form of(value, options) => ""
or functions that return error messages for failed validations; E.g.,
import {digitValidator} from 'fjl-validator';
const validateDigits = digitValidator({
messageTemplates: {
DOES_NOT_MATCH_PATTERN: x =>
`Only digits accepted. Value entered: "${x}".`
}
});
deepEquals(validateDigits('abcdef'), {
result: false,
messages: ['Only digits accepted. Value entered: "abcdef"']
})
; // true
value {*}
options {ValidationOptions}
@todoMessageTemplateCallback
's signature should bef(options, value)
not other way around (f(value, options)
). @todo Should be changed in later version of lib.
result {Boolean}
- Whether value passes validation or not.messages {Array.<String>}
- Validation error messages if any.value {*}
- Value that was validated.
options {ValidationOptions}
- Validation/Validator options.value {*}
- Value to be validated.
Library's version number.
- For commands see './package.json' scripts.
- Everything is in './src'.
- Distrubution is in './dist'.
- Docs are in './docs'.
Using jest
(see './package.json' scripts).
BSD 3 Clause - Included in sources.
-
- Zend/Validator - https://zendframework.github.io/zend-validator/intro/
- Removed methods ending with '$' also known as un-curried methods (use their curried counter parts instead).
- Updated build process to use babel 7.
- Added
lengthValidator
to the mix of validators.