Quick actions

cmd+k|ctrl+k

Navigation

Languages

Validate pipe

Snippet info

Language

JavaScript

Visibility

public

Author

paulkotov

Created

2019-11-18T15:59:43Z

Updated

2022-09-08T16:12:01.430261Z

const MIN_LENGTH = 3;

const PATTERN = /^([0-9]\d*)?$/;
const MIN = 2;
const MAX = 4;

let errors = [];
const errorMessages = {
  validateText: 'Requried!',
  validateMinLengthText: 'Too short!',
  validateMaxLengthText: 'Too long!'
};
const fieldValue = '';

const validateText = (text) => Boolean(text.length);
const validateMinLengthText = (text) => text.length > MIN_LENGTH;

const requiredField = (value) => Boolean(value) ? undefined : 'Requierd field';
const minLengthField = (value) => value.length > MIN_LENGTH ? undefined : 'Text is too short';
const patternValidate = (value) => PATTERN.test(value) ? undefined : 'Wrong pattern';
const maxValue = (value) => value <= MAX ? undefined : 'More than max';
const minValue = (value) => value >= MIN ? undefined : 'Less than min';

/**
 * Main validation
 */
const validator = (fns, errorMessages) => fieldValue => !fns.reduce((acc, validate) => {
    if (typeof validate !== 'function') {
        throw new Error('Not a function');
    }
    const isValid = validate(fieldValue);
    if (!isValid) {
        errors = errors.concat([errorMessages[validate.name]]);
    }
    acc.push(isValid);
    return acc;
}, []).some(result => !result);

const validation = (fns, fieldValue) => {
    let err;
    fns.forEach(func => {
        if (!err) {
            err = func(fieldValue);
            console.log('validate: ', err);
        }
    });
    return err;
};

const err = validation([patternValidate, minValue, maxValue], 3);
// console.log(validator([validateText, validateMinLengthText], errorMessages)(fieldValue));
// console.log(errors);

console.log('Err: ', err);

function validator2(...fns) {
  return (value) => {
    return fns.reduce((acc, item) => item(value) ? [...acc, item(value)] : acc, []);
  };
}

const validate = validator2(
    requiredField,
    minLengthField
);

console.log(validate('aaaaaaaaa'));
INFO