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.
- validate makes order in object
- new validators
- json
- boolean
- array
npm install als-schema
First, import als-schema
into your project:
const Schema = require('als-schema');
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;
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);
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 }
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.
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
.
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.
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' }
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
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;
Trims whitespace from both ends of a string.
const { trim } = Schema;
console.log(trim(' example ')); // Outputs: 'example'
Converts a string to lowercase.
const { lowercase } = Schema;
console.log(lowercase('EXAMPLE')); // Outputs: 'example'
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.
-
defValue
(string): The default value to return if the email is not valid.
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'
Slices a string or an array from the start
index up to, but not including, the end
index.
-
start
(Number): The starting index. -
end
(Number): The ending index (exclusive). -
defValue
(any): The default value to return if slicing is not possible.
const { slice } = Schema;
const sliceString = slice(1, 4);
console.log(sliceString('example')); // Outputs: 'xam'
Validates if a value is a string and checks its length between minLen
and maxLen
.
-
minLen
(Number): Minimum length. -
maxLen
(Number): Maximum length. -
defValue
(string): Default value to return if the validation fails.
const { string } = Schema;
const validateString = string(1, 5);
console.log(validateString('hello')); // Outputs: 'hello'
console.log(validateString('hello world')); // Throws error
Validates if a value is a number and checks if it's within the specified range.
-
min
(Number): Minimum acceptable value. -
max
(Number): Maximum acceptable value. -
defValue
(Number): Default value to return if the validation fails.
const { number } = Schema;
const validateNumber = number(1, 10);
console.log(validateNumber(5)); // Outputs: 5
console.log(validateNumber(15)); // Throws error
Validates if a value is an array. Returns the array if valid, otherwise throws an error or returns a default value if specified.
-
defValue
(Array): The default value to return if the input is not an array.
const { isArray } = Schema;
const validateArray = isArray();
console.log(validateArray([1, 2, 3])); // Outputs: [1, 2, 3]
console.log(validateArray('not an array')); // Throws error
Validates if a value is an object. Returns the object if valid, otherwise throws an error or returns a default value if specified.
-
defValue
(Object): The default value to return if the input is not an object.
const { isObject } = Schema;
const validateObject = isObject();
console.log(validateObject({key: 'value'})); // Outputs: {key: 'value'}
console.log(validateObject('not an object')); // Throws error
Validates if a value is a function. Returns the function if valid, otherwise throws an error or returns a default value if specified.
-
defValue
(Function): The default value to return if the input is not a function.
const { isFunction } = Schema;
const validateFunction = isFunction();
console.log(validateFunction(function() {})); // Outputs: [Function]
console.log(validateFunction('not a function')); // Throws error
Generates a unique identifier if the provided value is undefined
, otherwise returns the provided value.
const { id } = Schema;
console.log(id()); // Outputs: Generated ID
console.log(id('existingId')); // Outputs: 'existingId'
Checks if a value is defined (not undefined
or null
). If not, throws an error or uses the default value (defValue
) if provided.
-
defValue
(any): The default value to use if the value is not defined.
const { required } = Schema;
const validateRequired = required('default');
console.log(validateRequired('value')); // Outputs: 'value'
console.log(validateRequired(undefined)); // Outputs: 'default'
Checks if a value is defined (not undefined
or null
). If not, does not run the next validators/modifiers.
const { optional } = Schema;
const validateOptional = optional();
console.log(validateOptional(undefined)); // Outputs: undefined
console.log(validateOptional('value')); // Outputs: 'value'
Adds a value to a vars
object using a specified key, or the same key from the object if not specified.
-
newKey
(string): The key name in thevars
object (optional, defaults to the same key in the object).
const { addToVars } = Schema;
const addVar = addToVars('newKey');
console.log(addVar('value', 'key')); // Outputs: { newKey: 'value' }
Checks if a value is an instance of Date. Throws an error if not.
const { isDate } = Schema;
console.log(isDate(new Date())); // Outputs: [Date]
console.log(isDate('not a date')); // Throws error
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.
-
permitted
(Array): An array of permitted values. -
def
(any): The default value to return if the value is not in the list.
const { list } = Schema;
const validateList = list(['a', 'b'], 'default');
console.log(validateList('a')); // Outputs: 'a'
console.log(validateList('c')); // Outputs: 'default'
Returns true if a value is not undefined
or null
, otherwise false.
const { defined } = Schema;
console.log(defined('value')); // Outputs: true
console.log(defined(undefined)); // Outputs: false
Parses a JSON string into an object. If parsing fails, it returns a default object.
-
def
(Object): The default value to return if parsing fails.
const { json } = Schema;
const validateJson = json({ default: 'default' });
console.log(validateJson('{"key": "value"}')); // Outputs: { key: 'value' }
console.log(validateJson('invalid json')); // Outputs: { default: 'default' }
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.
-
defValue
(Boolean): The default value to return if the input is neither 'true'/'false' nor true/false.
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'
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.
-
validators
(Array): An array of validation functions to apply to each element of the array.
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
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}
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'
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