# als-schema

> A schema validation and transformation library for JavaScript.

Latest version **2.2.0** (published 2024-06-16) · ISC license · 0 weekly downloads

## Install

```sh
npm install als-schema
pnpm add als-schema
yarn add als-schema
bun add als-schema
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.2.0 |
| Published | 2024-06-16 |
| First published | 2023-06-08 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 45.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alex Sorkin |
| Maintainers | alexsorkin |
| Keywords | schema, validation, transformation, data-processing |

## Links

- npm: https://www.npmjs.com/package/als-schema
- npm.io page: https://npm.io/package/als-schema

## Dependencies (1)

- [als-uid](https://npm.io/package/als-uid.md) ^1.1.0

## Alternatives

- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@regle/core](https://npm.io/package/@regle/core.md) — 47.0K weekly downloads
- [typeof-arguments](https://npm.io/package/typeof-arguments.md) — 12.5K weekly downloads
- [@lokalise/projects-engine-contracts](https://npm.io/package/@lokalise/projects-engine-contracts.md) — 978 weekly downloads
- [@osjwnpm/nam-laboriosam-quibusdam](https://npm.io/package/@osjwnpm/nam-laboriosam-quibusdam.md) — 70 weekly downloads

## Recent versions

- 2.2.0 (latest) — 2024-06-16
- 2.1.1 — 2024-06-10
- 2.1.0 — 2024-05-12
- 2.0.0 — 2024-02-01
- 1.5.1 — 2023-12-19
- 1.5.0 — 2023-12-14
- 1.4.0 — 2023-12-09
- 1.3.0 — 2023-12-07
- 1.2.0 — 2023-11-30
- 1.1.0 — 2023-11-30
- 1.0.0 — 2023-11-29
- 0.5.8 — 2023-08-03
- 0.5.7 — 2023-06-26
- 0.5.6 — 2023-06-25
- 0.5.5 — 2023-06-18
- … 3 more at https://npm.io/package/als-schema/versions

## README

# 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

```bash
npm install als-schema
```

## Include module

First, import `als-schema` into your project:

```javascript
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`.

```html
<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:

```javascript
const { trim, lowercase, string, number, id, required } = Schema;
```


## Constructor and usage

Create a schema for your data:

```javascript
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:

```javascript
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:

```js
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

```javascript
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

```javascript
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

```javascript
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:

```javascript
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
```js
const { trim } = Schema;
console.log(trim('  example  '));  // Outputs: 'example'
```

## `lowercase`
Converts a string to lowercase.

### Example
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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
```js
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:
```js
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:
```js
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:

```js
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:
```js
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
```

---
_Source: https://npm.io/package/als-schema · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
