Package Exports
- als-schema
- als-schema/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (als-schema) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
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.
Installation
npm install als-schemaInclude 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 { trim, lowercase, slice, string, number, id, required, min, max, between, minLen, maxLen, email } = Schema;Method Descriptions
trim(value)
- Description: Trims whitespace from both ends of a string.
- Parameters:
value- The string to be trimmed. - Returns: Trimmed string.
- Throws: No exceptions thrown.
lowercase(value)
- Description: Converts a string to lowercase.
- Parameters:
value- The string to be converted. - Returns: Lowercase string.
- Throws: No exceptions thrown.
email(value)
- Description: Validates if value is valid email.
- Returns: value.
- Throws: Error if email is not valid.
slice(start, end)
- Description: Slices a string or an array from the
startindex up to, but not including, theendindex. - Parameters:
start- The start index;end- The end index. - Returns: A slice of the original string or array.
- Throws: Error if
startorendis not a number, or if the value is not a string or an array.
string(minLen, maxLen)
- Description: Validates if a value is a string and checks its length.
- Parameters:
minLen- Minimum length;maxLen- Maximum length. - Returns: The original string if it meets the criteria.
- Throws: Error if the value is not a string, or if its length is not within the specified range.
number(min, max)
- Description: Validates if a value is a number and checks its range.
- Parameters:
min- Minimum value;max- Maximum value. - Returns: The original number if it meets the criteria.
- Throws: Error if the value is not a number, or if it is not within the specified range.
id(value)
- Description: Generates a unique identifier if the provided value is
undefined. - Parameters:
value- The value to be checked. - Returns: The original value or a new unique ID.
- Throws: No exceptions thrown.
required(defValue)
- Description: Checks if a value is defined (not
undefinedornull). If not, uses the default value (defValue). - Parameters:
defValue- The default value. - Returns: The original value or the default value.
- Throws: Error if no value is provided and no default value is set.
optional
- Description: Checks if a value is defined (not
undefinedornull). If not, not running next valudators/modifiers.
min(minValue)
- Description: Validates if a number is at least the specified minimum value.
- Parameters:
minValue- The minimum value. - Returns: The original value if it meets the criteria.
- Throws: Error if the value is less than the minimum value.
max(maxValue)
- Description: Validates if a number is at most the specified maximum value.
- Parameters:
maxValue- The maximum value. - Returns: The original value if it meets the criteria.
- Throws: Error if the value is greater than the maximum value.
between(a, b)
- Description: Validates if a number is within a specified range.
- Parameters:
a- The start of the range;b- The end of the range. - Returns: The original value if it is within the range.
- Throws: Error if the value is outside the specified range.
minLen(minLen)
- Description: Validates if the length of a string is at least the specified minimum length.
- Parameters:
minLen- The minimum length. - Returns: The original value if it meets the criteria.
- Throws: Error if the string is shorter than the minimum length.
maxLen(maxLen)
- Description: Validates if the length of a string is at most the specified maximum length.
- Parameters:
maxLen- The maximum length. - Returns: The original value if it meets the criteria.
- Throws: Error if the string is longer than the maximum length.
addToVars(newKey)
- Description: Adding value to vars object
- Parameters:
newKey- the key name in vars (by default same key in obj). - Returns: The original value.
- Throws: No throwing errors.
Each of these methods can be used as part of the schema definition to enforce specific data types, ranges, and formats.
Example
const Schema = require('./Schema'); // Assuming Schema is in the same directory
const { trim, lowercase, slice, string, number, id, required, min, max, between, minLen, maxLen,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: min(0),
// Validating a numeric field to have a maximum value
rating: max(5),
// Validating a numeric field to be within a specific range
experience: between(1, 10),
// Ensuring a string field has a minimum length
bio: minLen(10),
// Ensuring a string field has a maximum length
shortBio: maxLen(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
emailfield is trimmed and converted to lowercase. - The
usernameis sliced to ensure it's not longer than 10 characters. - The
namemust be a string within a specific length range. - The
ageis validated as a number within a specified range. - An
idis generated if not provided. - The
statusfield is required, with a default value of 'active'. - The
scoreand rating are checked for minimum and maximum values, respectively. - The
experiencemust fall within a specified range. - The
bioand 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