als-schema

2.0.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.

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:

// Trims whitespace from both ends of a string.
Schema.trim(v,k,o,vars) 

// Converts a string to lowercase.
Schema.lowercase(v,k,o,vars) 

// Validates if value is string and valid email
Schema.email(defValue)(v,k,o,vars) 

// Slices a string or an array from the `start` index up to, but not including, the `end` index
Schema.slice(start, end, defValue)(v,k,o,vars)

// Validates if a value is a string and checks its length between minLength and maxLength.
Schema.string(minLen, maxLen, defValue)(v,k,o,vars)

// Validates if a value is a number and checks its range between minLength and maxLength.
Schema.number(min, max, defValue)(v,k,o,vars)

// Validates if a value is a array.
Schema.isArray(defValue)(v,k,o,vars)

// Validates if a value is a object.
Schema.isObject(defValue)(v,k,o,vars)

// Validates if a value is a function.
Schema.isFunction(defValue)(v,k,o,vars)

// Generates a unique identifier if the provided value is `undefined`
Schema.id(v,k,o,vars)

// Checks if a value is defined (not `undefined` or `null`). If not, uses the default value (`defValue`).
// throws Error if no value is provided and no default value is set
Schema.required(value)(v,k,o,vars)

// Checks if a value is defined (not `undefined` or `null`). If not, not running next valudators/modifiers.
Schema.optional()

// Adding value to vars object
// `newKey` - the key name in vars (by default same key in obj)
Schema.addToVars(newKey)(v,k,o,vars)

Each of these methods can be used as part of the schema definition to enforce specific data types, ranges, and formats.

  • defValue - default value. In case of error, if default value provided, returned default value. Otherwise throwed error.
  • v,k,o,vars
    • v - value
    • k - key
    • o - the object to validate
    • vars - custom vars object

Example

const Schema = require('./Schema'); // Assuming Schema is in the same directory
const { trim, lowercase, slice, string, number, id, required, email } = Schema;

const userSchema = new Schema({
    // Using trim and lowercase for the email field
    email: [trim, lowercase, email],

    // Using slice to get a substring of the username
    username: slice(0, 10),

    // Ensuring the name is a string with a minimum and maximum length
    name: string(2, 50),

    // Validating the age to be a number within a specific range
    age: number(18, 100),

    // Generating an ID if not provided
    id: id,

    // Making sure the field is provided, using a default value if not
    status: required('active'),

    // Validating a numeric field to have a minimum value
    score: number(0),

    // Validating a numeric field to have a maximum value
    rating: number(0, 5),

    // Validating a numeric field to be within a specific range
    experience: number(1, 10),

    // Ensuring a string field has a minimum length
    bio: string(10),

    // Ensuring a string field has a maximum length
    shortBio: string(0, 100)
});

// Example usage
const userData = {
    email: '  EXAMPLE@DOMAIN.COM  ',
    username: 'longusername1234',
    name: 'Alice Johnson',
    age: '25',
    id: undefined,
    status: null,
    score: 5,
    rating: 4.5,
    experience: 3,
    bio: 'Software developer with over 10 years of experience...',
    shortBio: 'Software developer'
};

const validatedData = userSchema.validate(userData);
console.log(validatedData);

In this example:

  • The email field is trimmed and converted to lowercase.
  • The username is sliced to ensure it's not longer than 10 characters.
  • The name must be a string within a specific length range.
  • The age is validated as a number within a specified range.
  • An id is generated if not provided.
  • The status field is required, with a default value of 'active'.
  • The score and rating are checked for minimum and maximum values, respectively.
  • The experience must fall within a specified range.
  • The bio and shortBio are validated for minimum and maximum lengths.

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

Package Sidebar

Install

npm i als-schema

Weekly Downloads

23

Version

2.0.0

License

ISC

Unpacked Size

33.5 kB

Total Files

13

Last publish

Collaborators

  • alexsorkin