standardschema / javascript Goto Github PK
View Code? Open in Web Editor NEWStandard schema validation for JavaScript
License: Other
Standard schema validation for JavaScript
License: Other
From #6 (comment), was thinking about it a bit before. Basically, need a new special type (it's kind of on the same level as Intersection
, in that it's a special construct) that anywhere in the validation process can retrieve the runtime value or use a raw value. E.g. a number or a reference to a number.
For example:
const createdSchema = compose([
new Types.Properties({
dateCreated: compose([new Types.Date()])
})
])
const userSchema = compose([
new Types.Properties({
username: compose([new Types.String(), new Types.Pattern('^[a-zA-Z0-9_-]+$')]),
password: compose([new Types.String(), new Types.MinLength(5), new Types.MaxLength(100)])
}),
createdSchema
])
When running validations and branching occurs (e.g. Types.Union
) it needs to clear the errors from previous unsuccessful branches.
I'm terrible at naming, but maybe someone can help me come up with something better?
schematica
skeema
One thing that's kind of tricky to implement, but nice to have is partial validation.
Example usecase: if I'm entering values in a form and I want to type check onBlur
for each field, but I also want to make sure that the final result shape is validate.
I could see do something like validate.only(...)
:
const validate = compile(new Types.Object({
properties: {
job: new Types.String({
pattern: '^[\\w:]+$'
}),
cron: new Types.String({
//pattern: '^\\d{1,2}:\\d{2}$'
}),
timezone: new Types.String(),
now: new Types.DateTime({
required: false
})
}
}))
const valid = await validate.only('timezone')('some string')
Could also be done with composition though
The ability to link to another defined type using URIs would be very useful in public API spaces. This would largely be related to #26 which would enable the ability to actually read these types at a given URI.
From #1, it'd be useful for serialising and deserialising to be able to visit types without implementing too much logic.
Enable a type to be composed from property rules and make fromJSON
and toJSON
simpler (remove duplication and sub-classing logic). Removes independent type classes and instead makes them a composition of their properties (with @type
coming first).
Would be useful for validation errors to contain the schema path - not just the assertion itself.
Trying out this library :-) It's a bit weird that pattern needs to be a string since it forces you to escape your regexp. Example:
const validate = compile(new Types.Object({
properties: {
job: new Types.String({ pattern: '^[\\w:]+$' }),
time: new Types.String({ pattern: '^\\d{1,2}:\\d{1,2}$' }),
timezone: new Types.String()
}
}))
Might be nice to make it support regexp too
It'd be awesome to add a Mutate
/Transform
rule that only transforms for the duration of the rules nested inside it. This would enable things like ToLower(Blacklist)
where the original casing is preserved when returning back upstream.
Edit: Oh, clever thing is now required
can skip the following checks immediately - exiting the middleware chain.
JSON.parse
)querystring.parse
)Enable conditional trees using If
rules. E.g. If(CheckUnique)
.
interface IfOptions {
left: any | Ref,
comparator: '==' | '!=' | '>=' | '<='
right: any | Ref
uses: Rule[]
}
new Types.Object({
properties: {
password: new Types.String({ minLength: 5, maxLength: 10 }),
confirmPassword: new Types.String({
uses: [new Types.If({ left: ref(), compator: '==', right: ref(['password'], 1) })]
})
}
})
Need to be able to compose types into each other to optimise the executed code path.
I just found a useful case where I want to store valid sub-schemas, but only when the result is successful. For example, I need [x, y, z]
to be set, but if one fails validation don't fail entirely - just use undefined
.
For example, it's currently:
new Types.Object({
patterns: {
'^...$': ...
}
})
Could re-use types and patterns instead:
new Types.Object({
propertyTypes: [
[
new Types.Uuid(),
new Types.Object()
]
]
})
Both implementations need to consider how intersections work.
Inverses the containing rules. E.g. a pass fails, while a failure passes. This would allow things like Not(Uuid)
.
interface NotOptions {
check: Rule
uses: Rule[]
}
Something more user-friendly - like type.string().required(false).minLength(100)
. At the end, it should probably expose a single function to collect the types and get the schema for compilation.
use[]
Traverse the type model and generate a JavaScript validation function.
Old version: https://github.com/standardschema/javascript/blob/aae7c023a958e489b5a83454521ad71c6dfe281a/src/validation.ts
Related to #13, but enable the ability to extend using raw objects. E.g. stringType._extend({ required: false })
.
Branch | Build failing 🚨 |
---|---|
Dependency | ts-jest |
Current Version | 19.0.4 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As ts-jest is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
The new version differs by 10 commits .
b19dda8
Bump version
eff4f7d
Merge pull request #144 from kulshekhar/138-jest-cache
9095b47
Create cache directory if it doesn't exist
ad37e83
Update badges
297ab81
Merge pull request #143 from kulshekhar/greenkeeper/initial
c5c0406
docs(readme): add Greenkeeper badge
ee2386e
chore(package): update dependencies
85b2896
Merge pull request #142 from kulshekhar/harden-tsconfig-comments-test
cbdb3f7
Check that tests for comments in tsconfig tests extended files
729f415
Harden tests for comments in tsconfig
See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
This would enable the ability to "omit" a field, especially during intersection. For example:
new Types.Compose({
items: [
userSchema
new Types.Object({
properties: {
password: new Types.Void()
}
}
}
})
Mostly just for the error schema - want to be able to serialise the errors without each person writing a schema for it.
Branch | Build failing 🚨 |
---|---|
Dependency | tslint-config-standard |
Current Version | 5.0.1 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As tslint-config-standard is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
Changed
no-unnecessary-callback-wrapper
, StandardJS (or ESLint) doesn't have a similar ruleThere is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Using a required: boolean
flag on properties doesn't make a lot of sense overall. It's useful, but it's kind of tricky. Instead, consider whether the Object
type should instead have an optionalProperties
array and we should introduce a Null
type for "null-able".
Branch | Build failing 🚨 |
---|---|
Dependency | typescript |
Current Version | 2.2.0 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As typescript is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
For release notes, check out the release announcement
For new features, check out the What's new in TypeScript 2.2.
For breaking changes, check out the Breaking changes in TypeScript 2.2 page.
For the complete list of fixed issues, check out the issues fixed in Typescript 2.2 RC and after Typescript 2.2 RC.
Download:
Special thanks to all contributors to this release:
The new version differs by 218 commits .
a29e8cf
Update LKG
1120971
Fix #14136: Make Object.create
return any
all the time
6b5c448
Merge pull request #14131 from Microsoft/release-2.2_default_import_name
125a8fa
Merge pull request #14133 from aozgaa/MissingPropertyFix-2.2
b62b467
add periods
f2770a1
widen type, index signature, and add tests
a4cf12e
cleanup
d9e0fff
use getBaseTypeOfLiteralType
150e2fb
add tests
f133a67
wip testing
2187e67
Get Widened Type
533262c
wip
ee13f31
Handle undefined import name
510b384
Update LKG
08fe20e
[release-2.2] use separate process to probe if drive is safe to watch (#14098) (#14124)
There are 218 commits in total. See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Defines the minimum and maximum number of keys allows on the object.
Looks like this doesn't work:
now: new Types.DateTime({
default: new Date()
})
Leads to:
TypeError: Value argument must be a reference or primitive value
Guessing it's related to default being on the Any time, but DateTime being more specific.
Three types of methods:
Serialising and deserialising can be completely synchronous, they would be based on structural type checking (none of the validation logic needs to occur). The tricky part here is picking which branch to use during serialisation/deserialisation (E.g. for union types). Maybe the structural checks can throw errors and pick the first branch that doesn't error? Also, sort union types by assignability (E.g. "a
is a subset of b
, but b
is not a subset of a
").
It'd be nice to remove the classes, but I think they'll just get more prominent as I add complexity (E.g. sort union types, proper intersection types). Could make it so the classes don't hold anything and move logic outside. E.g.
import { types, compile } from 'jaywalk'
const schema = {
type: 'string',
properties: {
username: {
type: 'string'
}
}
}
const validate = compile(types, schema)
Vs
import { Types, compile } from 'jaywalk'
const schema = new Types.Object({
properties: {
username: new Types.String()
}
})
const validate = compile(schema)
Currently there's a rough coupling going on. Instead, structural classes should be completely separated from rules. Every property on a structural class must be used from structural type checking, otherwise it should be a rule. Rules can be simplified, since they don't need things like description, meta, etc.
new Types.String({
uses: [
new Rules.MinLength(1),
new Rules.MaxLength(50),
new Rules.Matches('^a-zA-Z0-9_$')
]
})
Need to implement a visual mode for the type system (E.g. JSON) that be stored in plain text and restored from plain text. The most obvious implementation requires exposing a "type container" of the built-in types that allows instantiating multiple type containers that also support "user types" for restoring.
Providing an optional name for the schema could be handy when you have larger applications. Right now the validation error I get back doesn't help me pinpoint which schema has the error:
{ MultiError: Validation failed for "String#pattern" at "time"
at /Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/index.js:27:51
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
at Function.Module.runMain (module.js:577:11)
at Object.<anonymous> (/usr/local/lib/node_modules/async-to-gen/async-node:98:10)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
cause: undefined,
errors:
[ { ValidationError: Validation failed for "String#pattern" at "time"
at Object.error (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/index.js:18:23)
at /Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/types/string.js:83:27
at /Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:75:32
at dispatch (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:74:20)
at next (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:76:28)
at isString (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/types/string.js:47:12)
at /Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:75:32
at dispatch (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:74:20)
at next (/Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/utils.js:76:28)
at /Users/matt/Projects/standupjack.com/node_modules/jaywalk/dist/types/any.js:73:16
cause: undefined,
path: [Object],
type: 'String',
keyword: 'pattern',
assertion: '^\\d{1,2}:\\d{1,2}$',
value: '1030' } ] }
Need to be able to create Rule
instances for usage in uses: []
without having to re-specify options like default:
and required:
.
Branch | Build failing 🚨 |
---|---|
Dependency | tslint |
Current Version | 4.4.2 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As tslint is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
no-import-side-effect
(#2155)match-default-export-name
(#2117)no-non-null-assertion
(#2221)ban-types
(#2175)no-duplicate-super
(#2038)newline-before-return
(#2173)completed-docs
adds options for location, type, and privacy. Also adds interfaces, enums, types (#2095)no-inferrable-types
adds option ignore-properties
(#2178)typedef
adds options object-destructuring
and array-destructuring
options (#2146)member-ordering
adds option alphabetize
(#2101)no-trailing-whitespace
adds option ignore-jsdoc
(#2177)no-trailing-whitespace
adds option ignore-comments
option (#2153)no-inferrable-types
automatically remove inferrable type annotations (#2178)no-any
(#2165)noConsecutiveBlankLines
(#2201)object-literal-shorthand
(#2165)no-switch-case-fallthrough
handle break, throw, continue and return nested in block, if-else and switch (#2218)no-switch-case-fallthrough
allow empty case clauses before default clause (#2218)no-mergeable-namespace
ignore property types that can't be merged (#2105)object-literal-key-quotes
no need to quote a float if its .toString() is the same. (#2144)no-consecutive-blank-lines
Correctly apply fixes at EOF (#2239)quotemark
now handles escaped chars (#2224)no-switch-case-fallthrough
allow single line comment // falls through
(#2218)no-unbound-method
allows property access and binary expressions (#2143)There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Branch | Build failing 🚨 |
---|---|
Dependency | validator |
Current Version | 6.2.1 |
Type | dependency |
This version is covered by your current version range and after updating it in your project the build failed.
As validator is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪
The new version differs by 16 commits .
17b6c98
6.3.0
de9d17c
Update the changelog and readme
ee0a9bb
Merge pull request #622 from Diluka/patch-1
5b62a91
Merge pull request #627 from arpadszasz/master
8afd190
Merge branch 'master' into master
0024404
Merge pull request #630 from thabung/patch-1
6788363
isByteLength() counts UTF-8 bytes, closes #615
2b92393
Update isMobilePhone.js
f890d15
Add support for Romanian mobile phone numbers
e0de9e4
add HK‘s alias
cd92fb3
Allow floats like -.01, fixes #618
0a5335c
Additional stuff for #616
6dda6d9
Merge pull request #617 from ojengwa/patch-2
e21a7d1
Merge pull request #616 from ojengwa/patch-1
1b334ac
Update README.md
There are 16 commits in total. See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Any
@id
- for referencing across schema and to other schemasdescription
- user description of typeString
minLength
- string validationmaxLength
- string validationpattern
- string validationString
, Number
, Date
, DateTime
, Property
min
- minimum valid value (e.g. 1900-01-01
, aaa
, 1
)max
- maximum valid value (e.g. 2010-01-01
, bbb
, 9
)Intersection
, Union
types
- list of valid typesList
minItems
- minimum number of itemsmaxItems
- maximum number of itemsObject
properties
- list of valid propertiesadditionalProperties
- validate additional properties not matched (e.g. "force invalid here")Property
, Object
minProperties
- minimum matching properties when using key schemamaxProperties
- maximum matching properties when using key schemaProperty
key
- allow key to be a schema or primitive valuerequired
- equal to minProperties == 1
Tuple
tuple
- list of valid properties for ordered tupleCurrently the union type tries all branches and succeeds when one branch passes. Instead, it should use a structural check and do the full validation on a single branch.
Need to be able to specify dependencies within the system - most likely as a rule and using the refs feature.
new Types.Object({
properties: {
lat: new Types.Number({
required: false ,
uses: [
new Types.Depends({
on: [Utils.ref(['lng'], 1)]
})
]
}),
lng: new Types.Number({
required: false
})
}
})
Rules/types need a method to merge compatible sub-types into others. This would enable optimised intersections and also enable composed types.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.