Giter Club home page Giter Club logo

async-validate's People

Contributors

fabricioffc avatar tmpfs avatar viruschidai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

async-validate's Issues

Docs: Usage plugin section is refering to local path

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')
]);

ANN: Peer review 0.12.x

Prompted by issue #20 raised by @Oredi I decided to a do a full review of this package for the following reasons:

  • I am now using this package in the browser
  • The initial implementation was rushed to fulfill a need
  • It had been a while since the code was visited
  • I had some ideas for API improvements
  • There were outstanding features to be implemented
  • Relying on this package in private commercial projects
  • It appears other people are using this package

So the past few days have seen a lot of breaking changes as it moved from 0.1.x to 0.7.x:

  • Refactored rule function signature to function(cb)
  • Refactored to use a plugin system (browser)
  • Removed unnecessary standard rules
  • Removed obsolete ValidationError class, using Error instead
  • Removed keys processing option
  • Messages object does not expose clone() use Schema.clone() instead
  • Enum values array renamed from enum to list to avoid enum keyword

Other changes:

  • Removed async dependency, wrote minimal async iterator (browser)
  • Removed call to util.format created and used format-util (browser)
  • Added bail option
  • Support null type validation
  • Support additional field (see #18)
  • Support message as function (see messages)
  • Support message as object and extract message using error reason id (see #8)
  • Refactored iteration to allow validation of root object (see 8037e4a)
  • The method type (function) supports the range properties len, min and max (arity)
  • Support typed array shorthand 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.

/cc @MarcosRava @Oredi @filipedeschamps

Whats default for required?

It's run a validation when validation attribute does not have a required field and attribute value is undefined?

Support top-level array with resolve

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?

Assert on transient model data

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.

Make fields property required (remove shorthand)

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'}
  }
}

Update complete callback signature

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.

Code example for Rule function seems to be incorrect

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 = {
.....

Remove field name in custom error messages

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

Field property in custom Validation

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.

How to validate against other values?

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?

is support for ruleset X or ruleset Y supported?

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

npm run spec throws an error

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');

Implement match property

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.

Parallel Validation Of Fields.

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.

ANN: Discuss v1 release

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.

/cc @MarcosRava @Oredi @filipedeschamps

Allow array values to be subject to validation rules

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"}}}

Readme.md usage is incorrect

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.

Override global default error messages

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 :

https://tonicdev.com/ersefuril/5704d91504d77e13006a864f

Error fields key collision (tree)

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`

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 === ""

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.