Coder Social home page Coder Social logo

validate.js's Introduction

validate.js

Validate.js provides a declarative way of validating javascript objects.

For documentation please see validatejs.org/.

For issues and feature requests visit the issue tracker.

Archive Notice

As I do not work as a web developer professionally any longer I do not have the bandwidth to maintain this. This project will continue to live as is but no new features will be added and no bugs will be fixed. There are likely better and more modern alternatives around.

Building validate.js

Requirements

Build steps

  1. git clone [email protected]:ansman/validate.js.git
  2. cd validate.js
  3. npm install
  4. grunt build

This will build validate.min.js, validate.min.map and the docs folder.

Continuous testing

You can run continuous testing that runs the tests on file changes by running grunt watch or simply grunt.

If you want to just run the tests once you can do that by running grunt test.

Build status

Build Status Coverage Status

Contributing

Before opening a pull request please make sure your changes follow the contribution guidelines.

Users of validate.js

If your site, library or application uses validate.js and would like to be shown here please feel free to email [email protected] with the name and optionally a URL to the project and it will be added here.

validate.js's People

Contributors

andrewluetgers avatar andymantell avatar ansman avatar apokryfos avatar c100k avatar cellule avatar chetankothari avatar colinskow avatar deplabs-zyoung avatar dolmio avatar eisenbergeffect avatar franciscolourenco avatar jakerobers avatar jefbarn avatar jkeylu avatar johnturingan avatar jokero avatar kembuco avatar ktvvo avatar kyeotic avatar marfarma avatar minivercheevy avatar mondwan avatar naofumi-fujii avatar ogala avatar qoobaa avatar sanketparab-taulia avatar sebastianseilund avatar ujovlado avatar variousauthors 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  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

validate.js's Issues

Equality with another attribute

I'm wondering how to check the equality with another attribute? I've looked through the documentation and haven't found any possibility to define a custom validator only the dynamic one. Did I miss something?

Better support for arrays

This would be very useful for validating input from checkbox for example where you can choose more than one alternative.

The length validator already works with arrays (though the default message is for strings) but perhaps inclusion should (optionally?) support arrays saying that each item in the array must be in the inclusion list.

Another useful thing to validate would be uniqueness of the items in the array to make sure you haven't picked the same item twice.

Validatejs found Bug

When using validatejs , if the validate ( value or constraints ) contains ". " character which will not validate properly.For Example ,

values = {
basic.commandName: "",
basic.name: "",
workingDirectory: "cide"
};

constraints = {
basic.commandName: Object,
basic.name: Object,
workingDirectory: Object
};

To fix this one ,

Please remove check in your code in lune number between 282 .

        case '.':
        if (escape) {
          escape = false;
          key += '.';
        } else if (key in obj) {
          obj = obj[key];
          key = "";
        } else {
          return undefined;
        }
        break;

This case will use for some users .

Delete validate.async

validate and validate.async do the same thing. So validate should return a Promise that is resolved if the validation passes and is rejected if the validation failed.

Default values

Often I need to set custom message (or other fields) for all validators. Now I have to write every time:

myField1: {
    email: {
        message: 'invalidEmail'
    }
}
...

myField2: {
    email: {
        message: 'invalidEmail'
    }
}
...

It is better:

validators.defaults.email.message = 'invalidEmail';
...

myField1: {
    email: true
}
...

myField2: {
    email: true
}

Error when trying to validate sub attribute of null

I have a constraint looking like this:

  'copy.primaryColor':
    format:
      pattern: "^#(?:[0-9a-f]{3}){1,2}$"
      flags: "i"
      message: "must be a valid hex color"

The problem is that everything breaks if copy is null.

TypeError: Cannot use 'in' operator to search for 'primaryColor' in null
  at Function.v.extend.getDeepObjectValue (/Users/javve/Git/confetti/confetti-api/node_modules/validate.js/validate.js:310:18)
  at Function.v.extend.runValidations (/Users/javve/Git/confetti/confetti-api/node_modules/validate.js/validate.js:66:19)
  at Function.v.extend.async (/Users/javve/Git/confetti/confetti-api/node_modules/validate.js/validate.js:129:23)

Clean validated data

It would be great to use validate to clean the data a user sends in. Basically I want a way to whitelist attributes to make them optional. So for a user you should be able to pass in description, but not createdAt. Here is a example of how it could work:

data = 
  name: 'Test'
  description: 'Yaay'
  createdAt: 'omgomg'

constraints =
  name:
    presence: true
  description: true

validate.async(data, constraints).then (params) =>
  # params won't contain createdAt
  User.create(params)

Moment.js is there but still "Neither XDate or moment.js was found"

I don't use in my AngularJS app neither AMD nor Require so I just include moment.js. And after the validate.js is included. Still, I get "Neither XDate or moment.js was found" error.

This is where the problem is - line 659 (v. 0.3.2):
var moment = v.tryRequire("moment");

It returns null. But the global scope moment is defined.

Nested object magic interferes with dotted notation

Hi,

I think "dotted notation" (i.e. {"foo.bar": true} suffers from the magic surrounding nested objects.

  var constraints = {
    "foo\\.bar": {presence: true}
  };
  validate({"foo.bar": null}, constraints)
> "foo\\.bar": ["Foo bar can't be blank"]

Note the awkward backslashing, and the incorrect validation-error Foo bar can't be blank which should be foo.bar can't be blank

I've made a PR @ #47 that shows how dotted notation must currently be used.

Does this feature behave like you want it to? Or have I missed something that makes this much simpler? It would be nice to have a way to differentiate between nested objects and dotted notation, but I haven't made sense of the code itself yet to make the change myself so I wanted to ask here.

optional fields

I can't describe optional field in validators. I need cancel other validators if presence: false.

Better. Rename presence to required and copy logic from angular.js: empty data always valid if required not true.

Promise Validation is inconsistent

In synchronous validators returning a string indicates an error message. Promises should treat resolves just like returns, meaning a promise that resolving a string is analogous to a function that returns a string.

Async validators, though, require a promise to be rejected with a string. Resolving with a string is ignored. The different semantics mean that you cannot just return a call to validate(someStuff) inside of your promise, once your async work has completed. You have to wrap the result, and either resolve or reject according to it.

This is not consistent with standard promise semantics. Not only that, it complicates the code. It would be much easier to just return result inside of the promise code, knowing that if result is null an error won't be displayed, and if result is an error it will be displayed.

Promise with node.js is null

Hi,

I am using the framework sails.js for node.js. I am using validate.js that is a great library.

I just want to test the async feature.

I created a constraint:

exports.constraintNumericExist = {
    presence: true,

    numericality: true
};

And then I call validate.async(...

The issue is that I have the following error:

error: Sending 500 ("Server Error") response: 
 TypeError: object is not a function
    at Function.v.extend.async (backend/node_modules/validate.js/validate.js:190:14)

And the line is:

return new v.Promise(function (resolve, reject) {

I checked and Promise is null. Would you know why? Do I need to install another lib to support promise with node?

Thanks,

Conditional Validation

Any plans to support conditional validation paths, like rails' if: or unless: directives?

Not webpack/browserify friendly

I checked the code a bit and realized that the require function is cached, modified and wrapped. Is it really necessary ? Since the actual require is wrapped in a try catch, why not simple use the require function and catch if any error occurs?

see the error below

WARNING in ./~/validate.js/validate.js
Critical dependencies:
456:13-20 require function is used in a way, in which dependencies cannot be statically extracted
 @ ./~/validate.js/validate.js 456:13-20

You can see more info on good practices here https://github.com/umdjs/umd

collectFormValues fails in IE9

The collectFormValues function fails in IE9 as the dataset attribute is not supported. The code fails with the following error:

SCRIPT5007: Unable to get value of the property 'ignored': object is null or undefined

The offending code:

if (input.dataset.ignored !== undefined) {
    continue;
}

[FIXED] Demos

Dear Nicklas,
could you be so kind and add at least a couple of pure JS/HTML demos?
So far there's no easy way to use Validate.js right out of the box.

Numbers length validation

Hello there !
Thanks for this library, I find it very useful and very rich in its features ๐Ÿ‘
I was wondering if there was any way of validation a number's length.

I'm using a workaround as follows :

numericality : {
  onlyInteger : true,
  greaterThan : 9999
}

It would be more convenient to be able to write something similar to strings :

numericality : {
  onlyInteger : true
},
length : {
  minimum : 5
}

Thank you for your time,
Thomas

Promises and rejections

Thanks for a cool validation module.

One thing that bugs me is how validate.async() rejects with the errors. This is not analogous to how validate() works. It returns no matter the validation result, either with undefined for success or a hash of errors if not successful. It does not throw the errors. So validate.async should also do the same: Resolve with either undefined if successful or a hash of errors if not successful.

Rejecting the promise corresponds to throwing in validate(). It indicates an application error, not a validation error.

This goes for both validate.async and the promise custom async validators return.

First of all nothing should reject with random objects or strings. You should reject with a proper Error instance.

Secondly, it becomes a problem when the validation rejection gets mixed up with application errors. Worst case scenario is that an application error containing sensitive information is leaked to a user. Here's an example of that:

validate.validators.userExists = function(userId) {
  return db.query("SELECT id FROM users WHERE ?", [userId])
    .then(function(rows) {
      if (rows.length === 0) {
        throw 'User does not exist';
      }
    })
}

If db.query rejects, the db error object will be included in the final validation errors hash.

I would gladly submit a PR to fix this, if you want to take the library this way (I definitely think you should).

email validator with empty string slow?

Hey, I've been writing some unit tests for my node.js project and one of the tests is showing as slow quite often, 40-100ms. Basically its validating an empty string against an email. eg:

validate({email:""},  {
  email: {
    presence: true,
    email: true,
    length: {
      minimum: 6,
      maximum: 255
    }
  }
});

Running in the browser it seems to be about 15-20ms which isn't as bad but still seems pretty slow?

Bower Install Not Finding Git Repository

bower validate.js#* not-cached git://github.com/jaridmargolin/validate.js.git#*
bower validate.js#* resolve git://github.com/jaridmargolin/validate.js.git#*
bower validate.js#* ECMDERR Failed to execute "git ls-remote --tags --heads git://github.com/jaridmargolin/va
lidate.js.git", exit code of #128 fatal: remote error: Repository not found.

What is the validator for checkbox checked

Hey Guys,
I want to be able to validate my form only if the checkbox checked is set to true.
I'm using react:

what would be the constraint for that?
presence is obviously not an option and "equality : true" is not working either.

Thanks

Make easy to integrate with angular input[date]

I'm using angular, which when using input[date] forces the ng-model to be a Date() object.
AFAIK, validatejs expects the target object to be a "string date".

Wouldn't be nice to make validatejs a little intelligent to detect that the validated property has a Date in it, and pass it to momentjs ?

Or maybe there is something i'm missing and the solution is already there?

Promise chain friendly errors

Hi. I started using promises all over my code because it makes the code look beautiful. I really like this library but the problem is that errors are returned as Object not as instanceof some ValidationError class.

What I would propose is to wrap errors into validate.ValidationError class where you can still get an object calling toObject() method thus everything works the same way we just add a better support for promises.

Example:

  validate.async(req.body, contraints).then(function() {
    return Model.save(req.body);
  }).then(function(result) {
    res.status(201).json(result);
  }).catch(validate.ValidationError, function(err) {
    res.status(422).json(err);
  }).catch(function(err) {
    res.status(500).json(err);
  });

I would appreciate if we can do this small update. Thanks!

datetime filter not working properly

using

var result = validate(
      { data : "202015-01-19" },
      { data : { presence: true, datetime: { dateFormat: "YY-MM-DD" } }}
);

gives valid date..

  • with moment.js

Option 'flatten' is wrongly documented or handled

On the site it is stated that passing option 'flatten' will make library return flat array instead of nested objects. But actually when this option is enabled an object with numeric keys is returned (which looks like an array but missing length property for example).

// got
{"0":"Message"}
// instead of expected
["Message"]

Add validatorName to the list of error messages

It would be nice to be able to style error messages based on the validation type. Perhaps the return type could be set as on option.

Today:
{password: ["Password can't be blank"]}

Suggestion:
{password: [{validatorName:"length", errorMessage: "Password is too short (minimum is 6 characters)", value: "pass"}]}

The catalyst for wanting this change is a warning state where I suggest an email correction: "Did you mean comcast.net in place of comcast.com". This message would be interactive with a link to the corrected address.

Error message and automatically prepended attribute name

Thank you very much for this useful library. I'm currently working on my first JavaScript/React project, and the language and framework independence of validate.js is important.

Because of that pursuit for independence, I'm somewhat surprised that attribute names get prepended to error messages automatically. It seems to make assumptions about the way error messages are handled by the application. For instance, if I want to show the error message directly under the offending input field, having the attribute name as part of the message is kind of redundant. Is there a way around this?

Improve the datetime formatting and parsing

If we are to truly share validations between languages we need to be able to specify date formats that are library agnostic.

Perhaps they should be restricted to simpler formats only containing year, month, day, hour, minutes, second and timezone for portability.

This would also make it simpler to support more than one library and perhaps even the built in date parser in javascript.

presence validator against date attribute will complain even it's not empty

Following is a quick test case:

var validate = require("validate.js");

describe("validate", function ()
{
    describe("should give correct error for presence validator", function ()
    {
        it("when validating against date", function ()
        {
            var obj = {date: new Date()}, constrain = {date: {presence: true}};

            expect(validate(obj, constrain)).toBe(undefined);
        });
    });
});

validation return values only as String?

Is it intended behaviour that custom validators return only strings? I have written a slightly more complex validator, which checks whether date ranges do overlap or not. In order to provide meaningful hints to the user (by highlighting the conflicting form elemeents), i need to return more complex objects than just a string.

Is there a way to achieve this with validatejs? If yes, how?

As you can see in the snippet below, the validation method returns an object, which contains a message and the indices of begin and end. Using that, i wanted to highlight the corresponding form fields in the form.

// begin and end are both elements in an array. And i, j are the indices which refer to base/cmp in that array. 
// base.begin, base.end, cmp.begin and cmp.end are all moment.js objects.
if (base.begin.isAfter(cmp.begin)) {
    // if base.start is after cmp.start, then
    // base.begin has to be after cmp.end, too.
    var cmpEndsBeforeBase = base.begin.isAfter(cmp.end);
    if (!cmpEndsBeforeBase) {
        return {
            "message": cmp.title + " (" + cmp.end.format('YYYY MM DD') + ") ends after " + base.title + " starts (" + base.end.format('YYYY MM DD') + ")",
            "index": [i, j]
        }
    }
}

Custom messages for numericality validation

Hi guys,

I have the following validation:

code: {
  numericality: {
     greaterThanOrEqualTo: 1
  }
}

and I want to pass a custom message, like I do with other validations:

name: {
   presence: { message: 'Can not be blank'}
}

is it possible? I checked the documentation, but I couldn't find a way to do this.

Thanks in advance.

%{value} in format message

Firstly - awesome stuff you are building here, it's a big help!!

Am I doing something wrong - I'm trying to include the value of the field being tested in the custom error message. This works fine on inclusion but not on the 'format' check.

For example, this works great

currency: {
    presence: true,
    length: {is: 3},
    inclusion: {
        within: ccys,
        message: '%{value} is not a valid currency'
    },
    format: {
        pattern: /^[A-Z]{3}$/,
        message: 'is in an invalid format'
    }
}

But if I go with this

transaction_time: {
    presence: true,
    length: {is: 8},
    format: {
        pattern: /^[0-2][0-3]:[0-5][0-9]:[0-5][0-9]$/,
        message: '%{value} is in an invalid format '
    }
}

I get 'Transaction time %{value} is in an invalid format'

Am I doing something wrong or is it just not a feature at this point??

Thanks

Consider to add type converters

I'm researching Joi alternatives and found this lib. I like the crossplatform aim you set for this project (Joi sucks for frontend having 2+Mib). Unfortunately there is little meaning in validation without type coercion. If value is checked to be an integer it should be possible to use this as an integer.

Not validate as string, then apply type convertion manually, then use. It breaks the whole purpose of declarativeness in validation: you'll end up with the second deeply-nested declarative object with the same keys, and different values describing type convertion rules (semantically the same, as you've already said you want an integer)...

Async does not pass options to processValidationResults

If you install validate.js from npm (npm install validate.js):
validate.js, line: 133

var errors = v.processValidationResults(results);

In GIT repository:
validate.js, line: 133

var errors = v.processValidationResults(results, options);

Please, re-publish NPM package.

Thank you!

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.