als-schema

2.2.0 • Public • Published

als-schema

als-schema is a convenient tool for validating and transforming data in JavaScript. It offers a range of built-in methods for common validation tasks and allows for easy extension to meet specific requirements.

Change log for 2.2.0

  • validate makes order in object
  • new validators
    • json
    • boolean
    • array

Installation

npm install als-schema

Include module

First, import als-schema into your project:

const Schema = require('als-schema');

Browser

To use Schema in a browser, include it directly in your HTML file. Ensure that any dependencies, such as GenerateUid, are also included if they are not bundled with Schema.

<script src="node_modules/als-uid/index.js"></script>
<script src="node_modules/als-schema/index.js"></script>

In the browser, Schema will be available as a global object. You can access it directly:

const { trim, lowercase, string, number, id, required } = Schema;

Constructor and usage

Create a schema for your data:

const {required,lowercase} = Schema

const userSchema = new Schema({
   name: [String, required('default name')],
   email: [required(), lowercase],
   // ... other fields ...
});

Use the schema to validate and transform objects:

let userData = {
   name: 'Alex',
   email: 'EXAMPLE@DOMAIN.COM',
   // ... other fields ...
};

let validatedData = userSchema.validate(userData);

schema as array

The schema parameter can be array. Here is the example:

const schemaArr = ['key1','key2'] // like {key1:[],key2:[]} 
const schema = new Schema(schemaArr)
console.log(schema.validate({})) // { key1: undefined, key2: undefined }

Method: obj

The obj method is used to transform an array into an object based on the defined schema. This is particularly useful when you want to convert an array of values to an object where each value corresponds to a specific key as defined in the schema.

Example

const userSchema = new Schema({ name: [], age: [], email: [] });
const userDataArray = ['Alice', 30, 'alice@example.com'];

const userObject = userSchema.obj(userDataArray);
// userObject will be: { name: 'Alice', age: 30, email: 'alice@example.com' }

In this example, the obj method converts the userDataArray into an object using the keys defined in the userSchema.

Method: validate

The validate method is used to validate and transform an object based on the schema. This method applies all the validation and transformation functions specified in the schema to the corresponding fields in the object. Additionally, validate can also accept an array as input. In this case, it first uses the obj method to convert the array into an object based on the schema before applying the validations and transformations.

Example with an Object

const {required,string,number,trim,lowercase} = Schema
const userSchema = new Schema({
   name: [required(), string(3, 50)],
   age: [required(), number(0, 150)],
   email: [lowercase, trim]
});

const userData = { name: '  Bob  ', age: '28', email: ' BOB@EXAMPLE.COM ' };

const validatedData = userSchema.validate(userData);
// validatedData will be: { name: 'Bob', age: 28, email: 'bob@example.com' }

Example with an Array

const userSchema = new Schema({ name: [], age: [], email: [] });
const userDataArray = ['Alice', 30, ' ALICE@EXAMPLE.COM '];

const validatedData = userSchema.validate(userDataArray);
// validatedData will be: { name: 'Alice', age: 30, email: 'alice@example.com' }

In the first example, the validate method applies the specified validations and transformations to each field in the userData object. In the second example, it first converts

Schema Static Methods

The Schema class provides a range of static methods for validation and transformation. These methods can be used to define the behavior of each schema field.

To use these methods, import them from the Schema class:

const Schema = require('als-schema');
const {
  trim, lowercase, email, slice, string, number, 
  isArray, isObject, isFunction, id, required, 
  optional, addToVars, isDate, list, defined,
  json, boolean, array
} = Schema;

trim

Trims whitespace from both ends of a string.

Example

const { trim } = Schema;
console.log(trim('  example  '));  // Outputs: 'example'

lowercase

Converts a string to lowercase.

Example

const { lowercase } = Schema;
console.log(lowercase('EXAMPLE'));  // Outputs: 'example'

email

Validates if a value is a string and a valid email. Returns the email if valid, otherwise throws an error or returns a default value if specified.

Parameters

  • defValue (string): The default value to return if the email is not valid.

Example

const { email } = Schema;
const validateEmail = email('default@mail.com');
console.log(validateEmail('example@example.com'));  // Outputs: 'example@example.com'
console.log(validateEmail('invalid_email'));  // Outputs: 'default@mail.com'

slice

Slices a string or an array from the start index up to, but not including, the end index.

Parameters

  • start (Number): The starting index.
  • end (Number): The ending index (exclusive).
  • defValue (any): The default value to return if slicing is not possible.

Example

const { slice } = Schema;
const sliceString = slice(1, 4);
console.log(sliceString('example'));  // Outputs: 'xam'

string

Validates if a value is a string and checks its length between minLen and maxLen.

Parameters

  • minLen (Number): Minimum length.
  • maxLen (Number): Maximum length.
  • defValue (string): Default value to return if the validation fails.

Example

const { string } = Schema;
const validateString = string(1, 5);
console.log(validateString('hello'));  // Outputs: 'hello'
console.log(validateString('hello world'));  // Throws error

number

Validates if a value is a number and checks if it's within the specified range.

Parameters

  • min (Number): Minimum acceptable value.
  • max (Number): Maximum acceptable value.
  • defValue (Number): Default value to return if the validation fails.

Example

const { number } = Schema;
const validateNumber = number(1, 10);
console.log(validateNumber(5));  // Outputs: 5
console.log(validateNumber(15));  // Throws error

isArray

Validates if a value is an array. Returns the array if valid, otherwise throws an error or returns a default value if specified.

Parameters

  • defValue (Array): The default value to return if the input is not an array.

Example

const { isArray } = Schema;
const validateArray = isArray();
console.log(validateArray([1, 2, 3]));  // Outputs: [1, 2, 3]
console.log(validateArray('not an array'));  // Throws error

isObject

Validates if a value is an object. Returns the object if valid, otherwise throws an error or returns a default value if specified.

Parameters

  • defValue (Object): The default value to return if the input is not an object.

Example

const { isObject } = Schema;
const validateObject = isObject();
console.log(validateObject({key: 'value'}));  // Outputs: {key: 'value'}
console.log(validateObject('not an object'));  // Throws error

isFunction

Validates if a value is a function. Returns the function if valid, otherwise throws an error or returns a default value if specified.

Parameters

  • defValue (Function): The default value to return if the input is not a function.

Example

const { isFunction } = Schema;
const validateFunction = isFunction();
console.log(validateFunction(function() {}));  // Outputs: [Function]
console.log(validateFunction('not a function'));  // Throws error

id

Generates a unique identifier if the provided value is undefined, otherwise returns the provided value.

Example

const { id } = Schema;
console.log(id());  // Outputs: Generated ID
console.log(id('existingId'));  // Outputs: 'existingId'

required

Checks if a value is defined (not undefined or null). If not, throws an error or uses the default value (defValue) if provided.

Parameters

  • defValue (any): The default value to use if the value is not defined.

Example

const { required } = Schema;
const validateRequired = required('default');
console.log(validateRequired('value'));  // Outputs: 'value'
console.log(validateRequired(undefined));  // Outputs: 'default'

optional

Checks if a value is defined (not undefined or null). If not, does not run the next validators/modifiers.

Example

const { optional } = Schema;
const validateOptional = optional();
console.log(validateOptional(undefined));  // Outputs: undefined
console.log(validateOptional('value'));  // Outputs: 'value'

addToVars

Adds a value to a vars object using a specified key, or the same key from the object if not specified.

Parameters

  • newKey (string): The key name in the vars object (optional, defaults to the same key in the object).

Example

const { addToVars } = Schema;
const addVar = addToVars('newKey');
console.log(addVar('value', 'key'));  // Outputs: { newKey: 'value' }

isDate

Checks if a value is an instance of Date. Throws an error if not.

Example

const { isDate } = Schema;
console.log(isDate(new Date()));  // Outputs: [Date]
console.log(isDate('not a date'));  // Throws error

list

Checks if a value is in a permitted list. Returns the value if it's in the list, otherwise throws an error or returns a default value if specified.

Parameters

  • permitted (Array): An array of permitted values.
  • def (any): The default value to return if the value is not in the list.

Example

const { list } = Schema;
const validateList = list(['a', 'b'], 'default');
console.log(validateList('a'));  // Outputs: 'a'
console.log(validateList('c'));  // Outputs: 'default'

defined

Returns true if a value is not undefined or null, otherwise false.

Example

const { defined } = Schema;
console.log(defined('value'));  // Outputs: true
console.log(defined(undefined));  // Outputs: false

json

Parses a JSON string into an object. If parsing fails, it returns a default object.

Parameters

  • def (Object): The default value to return if parsing fails.

Example

const { json } = Schema;
const validateJson = json({ default: 'default' });
console.log(validateJson('{"key": "value"}'));  // Outputs: { key: 'value' }
console.log(validateJson('invalid json'));  // Outputs: { default: 'default' }

boolean

Converts a string or boolean value to a boolean. If the value is 'true' or true, it returns true. If the value is 'false' or false, it returns false. Any other value returns a specified default value.

Parameters

  • defValue (Boolean): The default value to return if the input is neither 'true'/'false' nor true/false.

Example

const { boolean } = Schema;
const validateBoolean = boolean('default');
console.log(validateBoolean('true'));  // Outputs: true
console.log(validateBoolean('false'));  // Outputs: false
console.log(validateBoolean('yes'));  // Outputs: 'default'

array

Applies a set of validators to each element in an array. This method does not check whether the input is an array; it assumes the input is an array and throws an error if not.

Parameters

  • validators (Array): An array of validation functions to apply to each element of the array.

Example

const { array, number, required } = Schema;
const validateArray = array([number(0, 10), required()]);
console.log(validateArray([1, 2, 3]));  // Outputs: [1, 2, 3]
console.log(validateArray([10, 20]));  // Throws error because 20 is out of range

Default value

You can add to schema default value, which not function to add in case, value not defined.

Example:

const schema = new Schema({
   name:['no name',String],
   active:[false,Boolean],
})

schema.validate({}) // {name:'no name',active:false}
schema.validate({name:'Alex'}) // {name:'Alex',active:false}

Or even like this:

const schema = new Schema({
   name:'no name',
   active:false
})

schema.validate({}) // {name:'no name',active:false}
schema.validate({name:'Alex'}) // {name:'Alex',active:false}

validateFn

Creates validation and modification function. Example:

const {validateFn,string} = Schema
const validateName = validateFn(['no name',string(2,20)])
validateName() // 'no name'
validateName('') // throw error
validateName('Alex') // 'Alex'

proxy method

Create object which validate and modifing properties in original object.

Example:

const schema = new Schema({
   name:['',string(2,20),lowercase],
   age:[optional,number(0,120)],
   canVote:[false,(v,k,o) => o.age && o.age >= 18,Boolean]
})

const obj = {name:'Alex',age:20}
const proxy = schema.proxy(obj)
console.log(obj.canVote) // true
proxy.age = 15
console.log(proxy.age === 15) // true
console.log(obj.canVote) // false
proxy.age = 125 // throws error

/als-schema/

    Package Sidebar

    Install

    npm i als-schema

    Weekly Downloads

    150

    Version

    2.2.0

    License

    ISC

    Unpacked Size

    47 kB

    Total Files

    13

    Last publish

    Collaborators

    • alexsorkin