Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
iamvalidator
Advanced tools
JS object validator
const Validator = require('iamvalidator');
const ValidatorError = Validator.IamValidatorError;
const Crypto = require('crypto');
const SALT = 'salt';
const UserValidator = new Validator({
type: 'object',
fields: {
nickname: {
type: 'string', //Nickname must be a string
min: 4, //with a minimum length of 4
max: 20, //and maximum length of 20
regexp: /^[a-zA-Z0-9_]+$/ //consisting of latin letters, digits and underscores
},
password: {
type: 'string', //password must be a string
min: 8, //with a minimum length of 8
max: 32, //and maximum length of 32
validate: (pwd) => {
//A password must contain at least one digin
if (!/[0-9]/.test(pwd)) {
throw new ValidatorError('PASSWORD_HAS_NO_DIGITS');
}
//A password must contain at least one lowercase letter
if (!/[a-z]/.test(pwd)) {
throw new ValidatorError('PASSWORD_HAS_NO_LOWERCASE_LETTERS');
}
//A password must contain at least one uppercase letter
if (!/[A-Z]/.test(pwd)) {
throw new ValidatorError('PASSWORD_HAS_NO_UPPERCSE_LETTERS');
}
},
transformAfter: (pwd) => {
//A password must be hashed after validation
return Crypto.createHash('sha1').update(pwd).update(SALT).digest('hex');
}
},
kittens: {
type: 'number',
min: 0,
transformBefore: (count) => {
//A value may be passed as a string, and it will be converted to number before any validation
return Number(count);
}
}
}
});
let user1 = {
nickname: 'Vasia',
password: 'pwd123PWD',
kittens: 1
};
let user2 = {
nickname: 'Petia)))',
password: 'pwd321PWD',
kittens: 0
};
let user3 = {
nickname: 'Slava',
password: '123',
kittens: '0'
};
let user4 = {
nickname: 'Slava',
password: 123,
kittens: '2'
};
try {
console.log(UserValidator.validate(user1));
/*{
nickname: 'Vasia',
password: 'f3e4c83aa7c6a1da18f1facf63dcdf21c3f8a881'
}*/
} catch (err) {
console.error(err);
}
try {
console.log(UserValidator.validate(user2));
} catch (err) {
console.error(err); //INVALID_STRING
}
try {
console.log(UserValidator.validate(user3));
} catch (err) {
console.error(err); //PASSWORD_HAS_NO_LOWERCASE_LETTERS
}
try {
console.log(UserValidator.validate(user4));
} catch (err) {
console.error(err); //TYPE_MISMATCH
}
Class representing a validator
Registers a validation function for the type specified.
validator
function is called with the following parameters:
TEMPLATE
-- validation templatedata
-- data to validatepath
-- path to field being validated (_root
, _root.field1
, _root.field1.sub_field2
, etc.)options
-- options passed to IamValidator.validate
methodThe function must return the validated data, or throw an error.
Validator object constructor. Accepts validation template, an object in the following form:
{
type: '<type>',
missing: 'ignore'|'default', //optional
extra: 'ignore', //optional
default: '<default_value>', //required if 'missing' is specified
values: []|Set, //optional, an array or set of values allowed for this object
validateBefore: (data, path, options, TEMPLATE, rootData, context) => {}, //optional, a custom validation function
validateAfter: (data, path, options, TEMPLATE, rootData, context) => {}, //optional, a custom validation function
transformBefore: (data) => {}, //optional, a custom function to transform the object before any validation
transformAfter: (data) => {}, //optional, a custom function to transform the object after validation
//fields specific for the <type>
}
Also accepts an array of validation templates. In case an array is passed, the values will be matched against every template consequently. The result of the first positive match will be returned. If no template matches, the error produced last will be thrown.
validateBefore
validates data after checking the type, but before any default validators.
validateAfter
validates data after default validators, just before transformAfter
.
Example:
[{
type: 'string',
regexp: /\d+/,
transformAfter: value => Number(value)
}, {
type: 'number'
}]
Variant notation is also supported:
{
type: 'variant',
variants: [{
type: 'string',
regexp: /\d+/,
transformAfter: value => Number(value)
}, {
type: 'number'
}]
}
If a hint
function is provided to template variants, raw data is checked against that function.
Templates with hint
returning true
-ish values are checked against first, no matter the actual order.
This may be used to optimize large template validation.
Example:
[{
type: 'object',
hint: rawValue => rawValue.kind === 'KIND_A',
fields: {
kind: {
type: 'string',
values: ['KIND_A', 'KIND_B']
}
// Dozens of fields for kind A
}
}, {
type: 'object',
hint: rawValue => rawValue.kind === 'KIND_B',
fields: {
kind: {
type: 'string',
values: ['KIND_A', 'KIND_B']
}
// Dozens of fields for kind B, different from the ones for kind A
}
}]
If an object field kind
has value 'KIND_B', it will be checked against the second template before the first one.
If hintStrict
option is provided,
validation will be performed only against the first template variant whose hint
matched raw data.
If no hint
matches, validation occurs as usual.
Performs validation.
Possible options are:
ignoreMissing
-- force missing fields to be ignoredarrayPathMode
-- use array path (like ['_root', 'x', 'y']
) instead of string path ('_root.x.y'
)context
-- a context passed to custom validation functions (empty array by default)Returns the validated data.
Class inheriting Node.js Error class. Represents a validation error.
Constant containing the error codes:
EXTRA_FIELDS
MISSING_DEFAULT_FIELD
MISSING_FIELD
ELEMENT_NOT_SPECIFIED
TYPE_MISMATCH
NO_VALIDATOR
NOT_IN_VALUES
Error object constructor.
extraData
is an optional argument, used to attach arbitrary extra data to an error object instance.
There are several builtin types. type-of-is
pachage is used to determine object's type.
A JavaScript object.
Example:
{
type: 'object',
fields: {
//nested fields
}
}
A JavaScript array.
Example:
{
type: 'array',
element: {
//element definition
}
}
A string.
Example:
{
type: 'string',
min: <M>, //optional, minimum string length
max: <N>, //optional, maximum string length
length: <K>, //optional, exact string length
regexp: <R> //optional, a regular expression to match the string against
}
A number.
Example:
{
type: 'number',
min: <M>, //optional, minimum value
max: <N>, //optional, maximum value
}
A boolean.
Example:
{
type: 'boolean'
}
An instance of JavaScript Date object.
Example:
{
type: 'date'
}
Null object.
Example:
{
type: 'null'
}
Any type can be allowed to be null.
Example:
{
type: 'date',
isNullable: true
}
Example:
class CustomClass {
constructor() {
//
}
}
{
type: CustomClass
}
registerValidator
may be used to validate instances of a class and preserve them as is. If no validator is specified,
'object'
validator is used by default. This leads to loss of some properties (like instance methods) as objects are
mapped (no reference equality of input and output data).
FAQs
JS object validator
The npm package iamvalidator receives a total of 1 weekly downloads. As such, iamvalidator popularity was classified as not popular.
We found that iamvalidator demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.