gateschema
v0.2.1
Published
GateSchema javascript implementation
Downloads
57
Maintainers
Readme
A small, simple and expressive schema builder and data validator.
Features
- simple and expressive syntax and keywords
- conditionally constraints
- supports async validation
- form generation: gateschema-form-vue, gateschema-form-react
- serialization
Quick Start
import _ from 'gateschema'
// Schema creation
const schema = _
.required
.map({
name: _
.required
.string
.notEmpty,
password: _
.required
.string
.notEmpty,
isRemember: _
.optional
.boolean
})
const userInput = {
// ....
}
// Data Validation
// callback style
schema.validate(userInput, (err) => {
if (err) {
// ...
}
// ...
})
// or promise style
schema
.validate(userInput)
.then(() => {
// ...
})
.catch((err) => {
// ...
})
// Serialization
console.log(schema.toJSON()) // or JSON.stringify(schema)
Install
npm install gateschema --save
API
see API
- Keywords
- Existance
- Base Types
- Complex Types
- Branching
- Utils
equal(path: string)
format(type: "date" | "date-time" | "hostname" | "uri" | "url" | "email" | "ipv4" | "ipv6")
length(range: number | [number] | [undefined, number] | [number, undefined] | [number, number])
max(value: number, isExclusive?: boolean)
min(value: number, isExclusive?: boolean)
not(schema: GateSchema)
notEmpty
pattern(regex: string | RegExp, flags?: string)
unique
- Other
- Methods
- Static Methods
Q&A
Custom messages and i18n
Require fields conditionally
const schema = _
.map({
employed: _
.optional
.boolean
})
.switch('/employed', [
{
// if `employed` is true
case: _
.value(true),
// then the input shoud be a map containing `employee` key
schema: _
.map({
employee: _
.required
.string
})
}
])
One of a field is required
const schema = _
.required
.map({
email: _
.switch('/phone', [
{
case: _.required, // if `phone` satisfy `_.required`
schema: _.optional // then `email` is optional
},
{
case: _.any, // else
schema: _.required.$msg('Please input email or phone') // `email` is required
}
])
.string
.format('email'),
phone: _
.switch('/email', [
{
case: _.required,
schema: _.optional
},
{
case: _.any,
schema: _.required.$msg('Please input email or phone')
}
])
.string
})
Another way
const schema = _
.required
.map({
email: _
.optional
.string
.format('email'),
phone: _
.optional
.string
})
.oneOf([
_.map({
email: _.required
}),
_.map({
phone: _.required
})
])
.$msg('Please input email or phone')
Changelog
See CHANGELOG
License
MIT