bob-validator

A library of validators

Usage no npm install needed!

<script type="module">
  import bobValidator from 'https://cdn.skypack.dev/bob-validator';
</script>

README

bob-validator

NPM version Downloads Build Status

A library of validators

Navigation


Installation and Using

Server-side usage

Install the library with:

$ npm install bob-validator
var _v = require('bob-validator');

// ...
let AllValidator = _v.AllValidator;

ES6:

import {
    // ...
    AllValidator
} from 'bob-validator';

Supported Function Constraints

var _v = require('bob-validator');

if(_v.func.isEmail('email@domain.com')){
    // Some code ...
}
Basic Constraints

These are the basic constraints: use them to assert very basic things about the value of properties or the return value of methods on your object.

  • isNotBlank(data) - Validates that a value is not blank, defined as not strictly false, not equal to a blank string and also not equal to null. To force that a value is simply not equal to null, see the isNotNull constraint.
  • isBlank(data) - Validates that a value is blank, defined as equal to a blank string or equal to null. To force that a value strictly be equal to null, see the isNull constraint. To force that a value is not blank, see isNotBlank.
  • isNotNull(data) - Validates that a value is not strictly equal to null. To ensure that a value is simply not blank (not a blank string), see the isNotBlank constraint.
  • isNull(data) - Validates that a value is exactly equal to null. To force that a property is simply blank (blank string or null), see the isBlank constraint. To ensure that a property is not null, see isNotNull.
  • isTrue(data) - Validates that a value is true. Specifically, this checks to see if the value is exactly true, exactly the integer 1, or exactly the string "1".
  • isFalse(data) - Validates that a value is false. Specifically, this checks to see if the value is exactly false, exactly the integer 0, or exactly the string "0".
  • isArray(data) - Validates that a value is array data type.
  • isBool(data) - Validates that a value is boolean data type.
  • isFloat(data) - Validates that a value is float data type.
  • isDouble(data) - Validates that a value is double data type.
  • isInt(data) - Validates that a value is integer data type.
  • isNumeric(data) - Validates that a value is numeric data type.
  • isObject(data) - Validates that a value is object data type.
  • isScalar(data) - Validates that a value is scalar data type.
  • isString(data) - Validates that a value is string data type.
  • isCallable(data) - isCallable Validates that a value is callable data type. Verify that the contents of a variable can be called as a function.
  • isLong(data) - Validates that a value is long data type. Alias of isInt.
  • isReal(data) - Validates that a value is real data type. Alias of isFloat.
  • isAlnum(data) - Validates that a value is alnum data type. Check for alphanumeric character(s).
  • isAlpha(data) - Validates that a value is alpha data type. Check for alphabetic character(s).
  • isDigit(data) - Validates that a value is digit data type. Check for numeric character(s). Checks if all of the characters in the provided string are numerical.
  • isLower(data) - Validates that a value is lower data type. Check for lowercase character(s). Checks if all of the characters in the provided string are lowercase letters.
  • isSpace(data) - Validates that a value is space data type. Check for whitespace character(s). Checks if all of the characters in the provided string creates whitespace.
  • isUpper(data) - Validates that a value is upper data type. Check for uppercase character(s). Checks if all of the characters in the provided string are uppercase characters.
  • isXdigit(data) - Validates that a value is xdigit data type. Check for character(s) representing a hexadecimal digit. Checks if all of the characters in the provided string are hexadecimal digits.
String Constraints
  • isEmail(data) - Validates that a value is a valid email address. The underlying value is cast to a string before being validated.
  • isLength(data, options) - Validates that a given string length is between some minimum and maximum value. Required options: {'min': 1, 'max': 100}.
  • isUrl(data) - Validates that a value is a valid URL string.
  • isPregMatch(data) - Validates that a value matches a regular expression. Required options: {'pattern': /^.+@\S+.\S+$/}.
  • isIp(data) - Validates that a value is a valid IP address.
  • isUuid(data, options) - Validates that a value is a valid Universally unique identifier (UUID) per RFC 4122. By default, this will validate the format according to the RFC's guidelines, but this can be relaxed to accept non-standard UUIDs that other systems (like PostgreSQL) accept. UUID versions can also be restricted using a whitelist. Optional options: {'versions': [1,2,3,4,5], 'strict': false}.
Number Constraints
  • isRange(data) - Validates that a given number is between some minimum and maximum number or date. Required options: {'min': 1, 'max': 100} or {'min': new Date(2015, 0, 1, 0, 0, 0, 0), 'max': new Date(2017, 0, 1, 0, 0, 0, 0)}.
Comparison Constraints
  • isEqualTo(data, options) - Validates that a value is equal to another value, defined in the options. To force that a value is not equal, see isNotEqualTo. This constraint compares using ==, so 3 and "3" are considered equal. Use isIdenticalTo to compare with ===. Required options: {'value': 100}.
  • isNotEqualTo(data, options) - Validates that a value is not equal to another value, defined in the options. To force that a value is equal, see isEqualTo. This constraint compares using !=, so 3 and "3" are considered equal. Use isNotIdenticalTo to compare with !==. Required options: {'value': 100}.
  • isIdenticalTo(data, options) - Validates that a value is identical to another value, defined in the options. To force that a value is not identical, see isNotIdenticalTo. This constraint compares using ===, so 3 and "3" are not considered equal. Use isEqualTo to compare with ==. Required options: {'value': 100}.
  • isNotIdenticalTo(data, options) - Validates that a value is not identical to another value, defined in the options. To force that a value is identical, see isIdenticalTo. This constraint compares using !==, so 3 and "3" are considered not equal. Use isNotEqualTo to compare with !=. Required options: {'value': 100}.
  • isLessThan(data, options) - Validates that a value is less than another value, defined in the options. To force that a value is less than or equal to another value, see isLessThanOrEqual. To force a value is greater than another value, see isGreaterThan. Required options: {'value': 100}.
  • isLessThanOrEqual(data, options) - Validates that a value is less than or equal to another value, defined in the options. To force that a value is less than another value, see isLessThan. Required options: {'value': 100}.
  • isGreaterThan(data, options) - Validates that a value is greater than another value, defined in the options. To force that a value is greater than or equal to another value, see isGreaterThanOrEqual. To force a value is less than another value, see isLessThan. Required options: {'value': 100}.
  • isGreaterThanOrEqual(data, options) - Validates that a value is greater than or equal to another value, defined in the options. To force that a value is greater than another value, see isGreaterThan. Required options: {'value': 100}.
Date Constraints
  • isDateFormat(data, options) - Validates that a value is a valid date. Required options: {'format': 'YYYY-MM-DD'}.
  • isDateTimeFormat(data, options) - Validates that a value is a valid datetime. Required options: {'format': 'YYYY-MM-DD HH:mm:ss'}.
  • isTimeFormat(data, options)- Validates that a value is a valid time. Required options: {'format': 'HH:mm:ss'}.
Collection Constraints
  • isIn(data, options) - This constraint is used to ensure that the given value is one of a given set of valid choices. Required options: {'choices': [1111, 'aaaaa', 3333, '123a'], 'strict': false}.
  • isInMultiple(data, options) - This constraint is used to ensure that the given value is one of a given set of valid choices. It can also be used to validate that each item in an array of items is one of those valid choices. Required options: {'choices': [1111, 'aaaaa', 3333, '123a'], 'strict': false, 'min': 1, 'max': 10,}.
  • isCount(data, options) - Validates that a given collection's (i.e. an array) element count is between some minimum and maximum value. Required options: {'min': 1, 'max': 10}.
  • isUniqueEntity(data, options) - Validates that a particular field (or fields) in entity is (are) unique. This is commonly used, for example, to prevent a new user to register using an email address that already exists in the system. Required options: {'fields': ['first_name', 'email'], 'repositoryData':[{"id":1,"first_name":"Diana","last_name":"Simmons","email":"dsimmons0@google.com"}, {"id":2,"first_name":"Earl","last_name":"Hunt","email":"ehunt1@wp.com"}]}.
  • isLanguage(data) - Validates that a value is a valid language Unicode language identifier (e.g. fr or zh-Hant).
  • isLocale(data) - Validates that a value is a valid locale. The "value" for each locale is either the two letter ISO 639-1 language code (e.g. fr), or the language code followed by an underscore (_), then the ISO 3166-1 alpha-2 country code (e.g. fr_FR for French/France).
  • isCountry(data) - Validates that a value is a valid ISO 3166-1 alpha-2 country code.
Financial and other Number Constraints
  • isBic(data) - This constraint is used to ensure that a value has the proper format of a Business Identifier Code (BIC). BIC is an internationally agreed means to uniquely identify both financial and non-financial institutions.
  • isCardScheme(data, options) - This constraint ensures that a credit card number is valid for a given credit card company. It can be used to validate the number before trying to initiate a payment through a payment gateway. Required options: {'schemes': ['AMEX', 'CHINA_UNIONPAY', 'DINERS', 'DISCOVER', 'INSTAPAYMENT', 'JCB', 'LASER', 'MAESTRO', 'MASTERCARD', 'VISA']}.
  • isCurrency(data) - Validates that a value is a valid 3-letter ISO 4217 currency name.
  • isLuhn(data) - This constraint is used to ensure that a credit card number passes the Luhn algorithm. It is useful as a first step to validating a credit card: before communicating with a payment gateway.
  • isIban(data) - This constraint is used to ensure that a bank account number has the proper format of an International Bank Account Number (IBAN). IBAN is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating transcription errors.
  • isIsbn(data, options) - This constraint validates that an International Standard Book Number (ISBN) is either a valid ISBN-10 or a valid ISBN-13. Optional options: {'type': 'isbn10'}.
  • isIssn(data, options) - Validates that a value is a valid International Standard Serial Number (ISSN). Optional options: {'caseSensitive': false, 'requireHyphen': false}.

⬆ back to top


Functions Usage Example

var _v = require('bob-validator');

if(_v.func.isEmail('email@domain.com')){
    // Some code ...
}

⬆ back to top


Classes Usage Example

var _v = require('bob-validator');

let NotBlankValidator = _v.NotBlankValidator;
let LengthValidator = _v.LengthValidator;
let CardSchemeValidator = _v.CardSchemeValidator;
let EmailValidator = _v.EmailValidator;
let DateValidator = _v.DateValidator;
let IpValidator = _v.IpValidator;
let LocaleValidator = _v.LocaleValidator;
let CountryValidator = _v.CountryValidator;
let LanguageValidator = _v.LanguageValidator;
let UrlValidator = _v.UrlValidator;
let CustomValidator = _v.CustomValidator;
let AllValidator = _v.AllValidator;

ES6:

import {
    NotBlankValidator,
    LengthValidator,
    CardSchemeValidator,
    EmailValidator,
    DateValidator,
    IpValidator,
    LocaleValidator,
    CountryValidator,
    LanguageValidator,
    UrlValidator,
    CustomValidator,
    AllValidator
} from 'bob-validator';
// Import ...

let CreditCardValidator = new CustomValidator({
    rules: [
        new NotBlankValidator({}),
        new LengthValidator({'min': 11, 'max': 19}),
        new CardSchemeValidator({'schemes': ['AMEX', 'CHINA_UNIONPAY', 'DINERS', 'DISCOVER', 'INSTAPAYMENT', 'JCB', 'LASER', 'MAESTRO', 'MASTERCARD', 'VISA']})
    ],
    message: 'Your error message'
});

let validators = {
    name: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new LengthValidator({'min': 2, 'max': 255})
        ]
    },
    email: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new EmailValidator({})
        ]
    },
    birthday: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new DateValidator({'format': 'DD.MM.YYYY'})
        ]
    },
    creditCard: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            CreditCardValidator
        ]
    },
    ip: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new IpValidator({})
        ]
    },
    locale: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new LocaleValidator({})
        ]
    },
    country: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new CountryValidator({})
        ]
    },
    language: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new LanguageValidator({})
        ]
    },
    homepage: {
        isRequired: true,
        rules: [
            new NotBlankValidator({}),
            new UrlValidator({})
        ]
    }
};

let data = {
    name: 'Leo Lane',
    email: 'leo.lane38@example.com',
    birthday: '03.07.1977',
    creditCard: '4111111111111111',
    ip: '8.8.8.8',
    locale: 'cy_GB',
    country: 'US',
    language: 'en_gb',
    homepage: 'https://github.com/alexeybob/bob-validator'
};

let _oec = new AllValidator({
    validators: validators,
    validationType: 'object',
    errorType: 'array'
});
_oec.validate(data);

if(!_oec.isValid()) {
    let errors = _oec.getErrors();
}

⬆ back to top


Schema Usage Example

var _v = require('bob-validator');

let AllValidator = _v.AllValidator;

ES6:

import {
    AllValidator
} from 'bob-validator';
// Import ...

let CreditCard = {
    rules: {
        NotBlank: {},
        Length: {
            'min': 11,
            'max': 19
        },
        CardScheme: {
            'schemes': ['AMEX', 'CHINA_UNIONPAY', 'DINERS', 'DISCOVER', 'INSTAPAYMENT', 'JCB', 'LASER', 'MAESTRO', 'MASTERCARD', 'VISA']
        }
    },
    message: 'Your error message'
};

let schema = {
    name: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Length: {
                'min': 2,
                'max': 255
            }
        }
    },
    email: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Email: {}
        }
    },
    birthday: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Date: {
                'format': 'DD.MM.YYYY'
            }
        }
    },
    creditCard: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Custom: CreditCard
        }
    },
    ip: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Ip: {}
        }
    },
    locale: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Locale: {}
        }
    },
    country: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Country: {}
        }
    },
    language: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Language: {}
        }
    },
    homepage: {
        isRequired: true,
        rules: {
            NotBlank: {},
            Url: {}
        }
    }
};

let data = {
    name: 'Leo Lane',
    email: 'leo.lane38@example.com',
    birthday: '03.07.1977',
    creditCard: '4111111111111111',
    ip: '8.8.8.8',
    locale: 'cy_GB',
    country: 'US',
    language: 'en_gb',
    homepage: 'https://github.com/alexeybob/bob-validator'
};

let _oec = new AllValidator({
    validators: schema,
    validationType: 'schema',
    errorType: 'array'
});
_oec.validate(data);

if(!_oec.isValid()) {
    let errors = _oec.getErrors();
}

⬆ back to top


Tests

$ npm test

⬆ back to top