tmpfs / async-validate Goto Github PK
View Code? Open in Web Editor NEWAsynchronous type validation for node and the browser
License: Other
Asynchronous type validation for node and the browser
License: Other
Following code should be
Schema.plugin([
require('../plugin/object'),
require('../plugin/string'),
require('../plugin/util')
]);
Schema.plugin([
require('async-validate/plugin/object'),
require('async-validate/plugin/string'),
require('async-validate/plugin/util')
]);
Prompted by issue #20 raised by @Oredi I decided to a do a full review of this package for the following reasons:
So the past few days have seen a lot of breaking changes as it moved from 0.1.x
to 0.7.x
:
function(cb)
keys
processing optionclone()
use Schema.clone()
insteadenum
to list
to avoid enum
keywordOther changes:
async
dependency, wrote minimal async iterator (browser)util.format
created and used format-util
(browser)bail
optionnull
type validationadditional
field (see #18)message
as function (see messages)message
as object and extract message using error reason id (see #8)method
type (function) supports the range properties len
, min
and max
(arity)values
(see #2)The readme has been rewritten to be up to date and reflect the changes, if any of you have time to review this work and feedback it would be much appreciated.
Whilst many aspects of the internal workings have been rewritten and changes will be required to dependent code (custom rule validation functions) and to reflect the new plugin system, I don't think any changes to existing schema rules should be necessary except the enum
breaking change noted above.
I am relatively happy with the new API and can't think of any changes at this point, the code also now has 100% coverage and may be tested in the browser (npm run spec
and open test/index.html
); so now is the time to request new features or find bugs/incompatibilities whilst I consider cutting a v1
.
Thanks for any help.
Shorthand for single and first processing options.
Hi guys!
Do you know if there's anything like JSON schema "additionalProperties" in async validate do refuse validation if there's any additional properties been sent?
Best regards!
cc @MarcosRava
It's run a validation when validation attribute does not have a required field and attribute value is undefined?
See #48.
The resolve function does not appear to be getting called with:
var mixed = {
type: 'array',
values: {
type: 'object',
resolve: resolve
}
}
Possible bug with iterating arrays at the top-level?
npm-debug.log is tracked as a missing file by git.
Ensure model data can be made available to all rule functions, possibly encourage a convention or use a transient
field.
This is for the use case when a validation rule needs to perform an operation (search database etc) but an existing object already provides the functionality, it may be passed in to validation processing and made available to rule functions.
On the thought we might have people contributing to this, I am wondering if it might be a good idea to introduce JsHinting and Style checking using JSCS on the code base.
Use expect
style.
Whilst the shorthand is convenient it makes the code more complex than it needs to be and will make schemas more readable by enforcing a fields
property.
This will mean that instead of:
{
name: {type: 'string'}
}
It must be:
{
fields: {
name: {type: 'string'}
}
}
To use function(err, res)
which is more idiomatic and will allow distinguishing internal processing errors from validation errors.
This is a breaking change and should be implemented in 0.6.x
series.
isValid()
is returning false in some situations for valid date format strings.
Hi,
May I checked if schema.error is correct? It appears to be undefined and when I checked lib/schema.js I see schema.ValidationError exposed but not schema.error
var schema = require('async-validate');
var ValidationError = schema.error;
var descriptor = {
.....
I've just followed your example to override default error messages :
var Schema = require('async-validate');
var descriptor = {
type: 'object',
fields: {
product:{type: "string", required: true}
}
};
var schema = new Schema(descriptor, {messages: messages});
var messages = require('async-validate/messages');
messages.required = "%s is a required field";
In my case, I don't wan't to display field name in error message, so this is what I've done :
messages.required = "REQUIRED !";
But when I'm validating a field (let say "product"), I've got this final error message :
"REQUIRED ! product"
Can't we avoid field name to be concatenated into final error message ?
Please see attached code here : https://tonicdev.com/56fb6a6381168d1100ac0b19/56fb6a6381168d1100ac0b1a
var descriptor = new Schema {
email: [
{type: "string", required:true, pattern: schema.pattern.email},
function(rule, value, callback, source, options) {
var errors = [];
Users.findOne({'email': value}, 'email', function(err, user){
if (!user) {callback(errors);}
errors.push(new ValidationError('Email Registered'));
callback(errors);
});
}
],
//There are other fields also
}
descriptor.validate(req.body, function(errors, fields){
if (errors){
console.log(errors);
return res.send(errors);
}
This gives a response like this:
[
{
"message": "Email Registered"
}
]
Rather than the typical:
[
{
"message" : "Email Registered",
"field" : "email",
}
]
I would like it would to return the is last mentioned manner as actually I don't to want to send response of errors rather I want to handle it in much cleaner way. So please help me as to what am I doing wrong. I think there is some problem in the creation of ValidationError.
Please look into it.
I am trying to validate a token against a user account, fetched by email.
const descriptor = {
type: 'object',
fields: {
email: {
type: 'string',
required: true,
test: function (cb) {
let regexp = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
if (!this.value.match(regexp)) {
this.raise('Invalid email address');
}
User.findOne({email: this.value}).then((user) => {
if (!user) {
this.raise('User not found');
}
cb();
}).catch((error) => {
throw error;
});
}
},
token: {
type: 'string',
required: true,
test: function (cb) {
// Need to get email here somehow
User.findOne({email: email, email_verification_token: this.value}).then((user) => {
if (!user) {
this.raise('Invalid token');
}
cb();
}).catch((error) => {
console.log(error)
this.raise(error.message)
});
}
}
}
};
I tried accessing this.source
but it only contains the token while validating token. Email is removed after email validation.
In general, I can think of many use cases where you want to validate a field against another. For example, end_date > start_date
.
How do I do this?
By allowing the type
property to be an array.
When compiled for the browser using browserify and minified it is weighing in at ~75KB, this should be reduced.
Async-validate seems great at first glance: Everything seems to be supported for my validation purposes (or otherwise I can extend it). However, I couldn't find 1 low-level 'validation routing primitive' for lack of a better word:
usecase: want to build validation for schema.org entities
some schema.org properties, such as performer allow the value to be polymorphic. In the example of performer
a value can either be a Person
or an MusicGroup
.
The JSON-LD way to mark this up is to specify the type as a @type
param.
So an object fragment displaying the performer
could be:
....
"performer":
{
"@type": "MusicGroup",
"name": "Chicago Symphony Orchestra",
"brand": "property specific to type=MusicGroup"
}
Or it could be:
"performer":
{
"@type": "Person",
"name": "some name",
firstName: "property specific to type=Person"
}
Or it could even be:
...
"performer": [
{
"@type": "MusicGroup",
"name": "Chicago Symphony Orchestra",
"brand": "property specific to type=MusicGroup"
},
{
"@type": "Person",
"name": "some name",
firstName: "property specific to type=Person"
}
],
Logically, Person would have different validation rules than Organization.
What I'd like to find a solution to is to be able to define a ruleset for both Organization and Person and select the proper ruleset based on some condition, here: the value of @type
Is this supported currently, and if not would you consider a pull request? If the latter, any pointers on where best to start digging?
Related: when defining an array of objects, is there a way to define the type of the items inside the arrays? I.e: type=array
+ items="Object"
, or in the above example type=array
+ items=[Person,Organization]
might make sense for instance
Used to support local time rather than UTC in date type.
npm run spec is throwing an error.
It appears that some requires for browserify no longer exists.
Are they no longer required?
require('./spec/transform');
-require('./spec/type');
require('./spec/undef');
-require('./spec/validator');
Apply a rule to multiple fields of a source object using a regexp match on field name, this allow the use case such as:
{match:/^address[0-9]{1,1}$/}
When you have fields named address0
, address1
etc. it becomes much easier to share the rule across the properties.
So that users could validate argument length (arity) for the function.
Prevent issues such as #37.
To be consistent with the other native data types and allow a small optimization.
If the input by the user has multiple fields which need to query database for validation then having those validation for each field run in parallel be very helpful and relatively fast.
I am thinking implementing that using modules such as async would be very easy. Hope you can implement this feature.
Thanks.
Allow validating schemas, draft in c02c8c9.
The last bug I am aware of was fixed recently in 0.12.3
, see #33.
For a list of all the recent breaking changes see #30.
The package should be able to validate any javascript object (asynchronously when necessary) has 100% code coverage and is well documented.
I intend to implement #49 and #54 before a v1 release, however if there are features that anyone believes are essential please let me know here, of course any bug reports are welcome too :)
I will research better i18n/messages support (gettext
/jed
etc) for a v2.
Thanks.
So that the type
field may be an array such as: [Number, Boolean, 'string', function Component(){}]
.
This can already be done using the deep validation logic but it may be useful to validate each array entry with the same validation rule.
The typical use case would be when expecting an array whose values are all of the same type.
Something like:
{array:{type:"array", required: true, values:{type:"number"}}}
It appears that the README.md is using mdp to generate the readme from the files in doc/. I took a look at doc/usage.js. And it shows the following code below
var Schema = require('..')
, descriptor = {name: {type: "string", required: true}}
I believe it should be
var Schema = require('async-validate')
, descriptor = {name: {type: "string", required: true}}
I will modify doc/usage.js and do a PR.
Please correct me if I'm wrong, documentation is not clear for me on a specific point.
I tried to apply your example to override all error messages by custom messages.
So, here is your example :
var Schema = require('async-validate')
, messages = require('messages-es')
, descriptor = {
type: 'object',
fields: {
name:{type: "string", required: true}}
}
}
, schema = new Schema(descriptor, {messages: messages});
I tried to clone all default messages and override them. I also tried to define only a small subset of messages to override, still have default error message.
Maybe I did a mistake when redefining messages, so you can find a running example here :
This was implemented by passing rules as a processing option but should be done declaratively.
Rule function callback now accepts err
to indicate that an internal processing error occured, idiomatic async style, aborts processing.
When a nested field uses the same name as a field at a higher level it would not be possible to distinguish that the error occurred on different properties, consider constructing a tree structure for keyed errors.
empty string should be raised when rules include required
,in utils.js ,function required should be
if (!this.isRoot() && this.rule.required && (!this.source.hasOwnProperty(this.field) || this.value === undefined || this.value === null || this.value === ""))
notice the this.value === ""
Reduce readme size (toc is too long), prevent header name collisions.
To validate schema files against the system schema.
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.