Giter VIP home page Giter VIP logo

sails-hook-validation's Introduction

sails-hook-validation

Build Status

Custom validation error messages for sails model with i18n support. Its works with callback, deferred and promise style model API provided with sails.

Note:

  • This requires Sails v0.11.0+. If v0.11.0+ isn't published to NPM yet, you'll need to install it via Github.
  • sails-hook-validation work by patch model static validate(), create(), createEach(), findOrCreate(), findOrCreateEach() and update().
  • To have custom error messages at model instance level consider using sails-model-new.
  • sails-hook-validation opt to use error.Errors and not to re-create or remove any properties of error object so as to remain with sails legacy options

Installation

$ npm install --save sails-hook-validation

Usage

Use without i18n

Add validationMessages static property in your sails model

//this is example
module.exports = {
    attributes: {
        username: {
            type: 'string',
            required: true
        },
        email: {
            type: 'email',
            required: true,
            unique: true
        }
    },
    //model validation messages definitions
    validationMessages: { //hand for i18n & l10n
        email: {
            required: 'Email is required',
            email: 'Provide valid email address',
            unique: 'Email address is already taken'
        },
        username: {
            required: 'Username is required'
        }
    }
};

Use with i18n

Add validation messages into config/locale files following modelId.attribute.rule. If model contains any validationMessages definition, they will take precedence over locale defined messages.

Example

//define your model in api/model/Authentication.js
module.exports = {
    attributes: {
        username: {
            type: 'string',
            required: true
        },
        email: {
            type: 'email',
            required: true,
            unique: true
        },
        birthday: {
            type: 'date',
            required: true
        }
    }
};

Then define validation messages per locale

//in config/locale/en.json
{
    "authentication.email.required": "Email is required",
    "authentication.email.email": "Provide valid email address",
    "authentication.email.unique": "Email address is already taken",
    "authentication.username.required": "Username is required",
    "authentication.username.string": "Username is must be a valid string",
    "authentication.birthday.required": "Birthday is required",
    "authentication.birthday.date": "Birthday is not a valid date"
}

//in config/locale/sw.json
{
    "authentication.email.required": "Barua pepe yahitajika",
    "authentication.email.email": "Toa barua pepe iliyo halali",
    "authentication.email.unique": "Barua pepe tayari ishachukuliwa",
    "authentication.username.required": "Jina lahitajika",
    "authentication.username.string": "Jina lazima liwe ni mchanganyiko wa herufi",
    "authentication.birthday.required": "Siku ya kuzaliwa yahitajika",
    "authentication.birthday.date": "Siku ya kuzaliwa sio tarehe"
}

Now you can call model static

  • create()
  • createEach()
  • findOrCreate()
  • findOrCreateEach()
  • update()
  • and other static model method that invoke Model.validate().

If there is any validations or database errors sails-hook-validation will put your custom errors message in error.Errors of the error object returned by those methods in your callback or promise catch.

create()

//anywhere in your codes if
//you invoke
 User
    .create({}, function(error, user) {
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.Errors.email).to.exist;

        expect(error.Errors.email[0].message)
            .to.equal(User.validationMessages.email.email);

        expect(error.Errors.email[1].message)
            .to.equal(User.validationMessages.email.required);


        expect(error.Errors.username).to.exist;
        expect(error.Errors.username[0].message)
            .to.equal(User.validationMessages.username.required);

        done();
    });

createEach()

User
    .createEach([{
        email: faker.internet.email(),
        username: faker.internet.userName()
    }, {
        email: 'otherExistingModelEmail',
        username: username
    }])
    .catch(function(error) {
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.Errors.email).to.exist;

        expect(error.Errors.email[0].message)
            .to.equal(User.validationMessages.email.unique);

        done();
    });

findOrCreate()

User
    .findOrCreate({
        email: faker.internet.email()
    }, {
        email: 'otherExistingModelEmail',
        username: username
    })
    .exec(function(error, user) {
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.Errors.email).to.exist;

        expect(error.Errors.email[0].message)
            .to.equal(User.validationMessages.email.unique);

        done();
    });

findOrCreateEach()

User
    .findOrCreateEach(
        [{
            email: faker.internet.email()
        }], [{
            email: 'otheExistingModelEmail',
            username: username
        }]
    )
    .catch(function(error) {
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.Errors.email).to.exist;

        expect(error.Errors.email[0].message)
            .to.equal(User.validationMessages.email.unique);

        done();
    });

update()

User
    .update({
        email: 'modelEmail'
    }, {
        email: 'otherExistingModelEmail'
    }, function(error, user) {
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.Errors.email).to.exist;

        expect(error.Errors.email[0].message)
            .to.equal(User.validationMessages.email.unique);

        done();
    });

Testing

  • Clone this repository

  • Install all development dependencies

$ npm install
  • Then run test
$ npm test

Contribute

Fork this repo and push in your ideas. Do not forget to add a bit of test(s) of what value you adding.

Licence

The MIT License (MIT)

Copyright (c) 2015 lykmapipo & Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

sails-hook-validation's People

Contributors

armellarcier avatar broderix avatar einfallstoll avatar isery avatar kinsi55 avatar lykmapipo avatar mbrio avatar rishabhmhjn avatar robertrossmann avatar seitk avatar shkryob 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

sails-hook-validation's Issues

Can't see custom errors

Hi again,

I understand that error.Errors is added to the response, but custom error messages are never being sent.

This is because sails will serialize the error object to JSON. It removes at the same time the custom message you added.

Please test the spec below to understand what I mean. I serialize to JSON and parse again and you will see error.Errors will disappear.

describe('Hook#create JSON serialization errors', function() {

        it('should throw unique error message after being serialized to JSON using stringify', function(done) {

            User
            .create({
                email: email,
                username: username,
                birthday: faker.date.past()
            }, function(error, user) {
                var errorJSON = JSON.stringify(error);
                error = JSON.parse(errorJSON);
                expect(error.Errors.email).to.exist;

                expect(error.Errors.email[0].message)
                .to.equal(User.validationMessages.email.unique);

                done();
            });
        });


        it('should throw unique error message after being serialized to JSON using toJSON', function(done) {

            User
            .create({
                email: email,
                username: username,
                birthday: faker.date.past()
            }, function(error, user) {
                var errorJSON = error.toJSON();
                error = JSON.parse(errorJSON);
                expect(error.Errors.email).to.exist;

                expect(error.Errors.email[0].message)
                .to.equal(User.validationMessages.email.unique);

                done();
            });
        });

    });

Does not work with blueprints

Standard errors works with blueprints and return json error object, but sails-hook-validation return 500 error with no validation details by default.

this module does not appear to work

model:

module.exports = {
    attributes: {

        email: {
            type: 'email',
            required: true,
            unique: true
        },
        password: {
            type: 'string',
            minLength: 6,
            maxLength: 256,
            required: true
        },
        username: {
            type: 'string',
            minLength: 2,
            maxLength: 20,
            required: true,
            unique: true
        },
    },
    validationMessages: { //hand for i18n & l10n
        email: {
            required: 'Email is required',
            email: 'Provide valid email address',
            unique: 'Email address is already taken'
        },
        username: {
            required: 'Username is required'
        }
    },
}

in the controller I used User.save() and User.update() and neither "err" had a property of "error"

       user.save(function(err){
        if(err){ 
            console.log("-->",err.error);
            return res.serverError();
        }
        req.user=user;
        userProfilePage(req,res);
      })

log: --> undefined
err contains:

 Details:  Details:  Invalid attributes sent to Users:
 • email
   • `undefined` should be a email (instead of "", which is a string)
   • "required" validation rule failed for input: ''

not very useful

finally, using update:

      User.update({ id: req.user.id }, { email: "fdkljajklfdas" })
          .exec(function(error, user){
          console.log("->",error);
          console.log("-->",user)
          res.send('...');
        })

error is the same object as usual
and error.error is of course undefined.

undefined ValidationError field for waterline returned error.

Hi,
I'm not sure if this classifies as an issue. I have a Sails v.11.0 project and have installed this validation module. Seeing it not working as expected in my particular case (an update scenario) I went with the debugger and traced my problem to the patched 'update.js' in this module, line 42:

if (error.ValidationError) {
                        error.Errors =
                            validateCustom(model, error.ValidationError);
                    }

The error coming from Waterline after failed update does not have any ValidationError field. It basically has a 'details' field: "Details: MongoError: E11000 duplicate key error index: mydb.user.$email_1 dup key: { : "[email protected]" }\n"' and besides this no other relevant attribute that can be linked to a validator module.
Am I missing something? As far as I can see my sails' waterline module is of the same version as the one listed on github.

Not adding custom messages in Sails v1.0.0-36

Hi. I can't seem to get this hook to work in Sails v1.0.0-36. Here's what I have.

Model EstablishmentClue

module.exports = {

  attributes: {

    name: {
      columnName: 'name',
      type: 'string',
      required: true,
    },

  ...

  },

  validationMessages: {
    name: {
      required: 'Name is required',
    },
  },

};

In sails console:

sails> EstablishmentClue.create({}).exec(console.log);
Error (E_UNKNOWN) :: Encountered an unexpected error
    at new WLError (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/sails-hook-validation/node_modules/waterline/lib/waterline/error/WLError.js:26:15)
    at Object.module.exports.patch (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/sails-hook-validation/lib/WLValidationError.js:8:13)
    at /Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/sails-hook-validation/lib/create.js:66:48
    at _.extend._WLModel (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/waterline/lib/waterline/methods/create.js:155:20)
    at parley (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/parley/lib/parley.js:111:5)
    at newConstructor.create (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/waterline/lib/waterline/methods/create.js:130:10)
    at newConstructor.create (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/sails-hook-validation/lib/create.js:47:14)
    at module.exports.Deferred.exec (/Users/Lucas/CompuDharma/treasuretown/treasuretown_web/node_modules/sails-hook-validation/node_modules/waterline/lib/waterline/query/deferred.js:477:16)
    at repl:1:30
    at ContextifyScript.Script.runInThisContext (vm.js:44:33)
    at REPLServer.defaultEval (repl.js:239:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:433:10)
    at emitOne (events.js:120:20)
    at REPLServer.emit (events.js:210:7)
    at REPLServer.Interface._onLine (readline.js:278:10)
    at REPLServer.Interface._line (readline.js:625:8)
    at REPLServer.Interface._ttyWrite (readline.js:904:14)
    at REPLServer.self._ttyWrite (repl.js:502:7)
    at ReadStream.onkeypress (readline.js:157:10)
    at emitTwo (events.js:125:13)
    at ReadStream.emit (events.js:213:7)
    at emitKeys (internal/readline.js:417:14)
    at emitKeys.next (<anonymous>)
    at ReadStream.onData (readline.js:1005:36)
    at emitOne (events.js:115:13)
    at ReadStream.emit (events.js:210:7)
    at addChunk (_stream_readable.js:250:12)
    at readableAddChunk (_stream_readable.js:237:11)
    at ReadStream.Readable.push (_stream_readable.js:195:10)
    at TTY.onread (net.js:586:20)

When I log error.toJSON() I get this:

{ error: 'E_UNKNOWN',
  status: 500,
  summary: 'Encountered an unexpected error',
  Errors: undefined }

Any thoughts on why the custom error messages aren't attaching?

Model.validation don´t return Errors

Hi, I am implementing a app using i18n and Sails-hook-validation, everything works fine except when I try with MyModel.validation function. The functions create and update return the translated validation messages in Errors hash.
I had tested as static method and instance method and both has the same problem. Could you help me ?

Not working with sails blueprint

i just installed the package and call the blueprint API. it is throwing error. not able to understand this behaviour.
after that i too added validation in en.json still not working.

Installation error

as soon as I run

npm install --save sails-hook-validation

I can no more lift the sail. I get this error instaead

error: Error: Cannot find module 'sails/node_modules/waterline/lib/waterline/query/deferred'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/Iman/Documents/projects/squirl/squirl-server/node_modules/sails-hook-validation/lib/create.js:5:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/Iman/Documents/projects/squirl/squirl-server/node_modules/sails-hook-validation/index.js:10:14)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

Didn't work with async function's try catch

(async function() {
      try {
        // update Store
        if (paramStore.id) {
          const finded = await Store.findOne(paramStore.id);
          _.assign(finded, paramStore);
          finded.save();
        }else {
          // add Store
          await Store.create(paramStore);
        }
        return res.ok();
      } catch (err) {
        sails.log.error(err);
        sails.log.error(err.Errors);
        return res.serverError(err);
      }
    })();

the err.Errors is undefined.

Throw Custom Error

Hello, first of all thanks for this useful package 👍

Then, I'm running in couple of problems and I was wondering if someone had already went trough these:

  1. For some model I have a complex creation logic and I want so skip standard validation for some creation flows. For doing this I have custom beforeCreate or beforeValidate for some models. What I would like to do is to manually throw your "patched" validation error if some conditions occurs. Is it possible? How?

  2. In my controllers when I return a response in json I check whether or not there are errors. I check error.Errors in case a validation error occurs. But this is not always the case, and in many cases the structure of the errors messages are really different. How to manage this?
    So far I've came to a simple

var errors = err.Errors || err.message || "Unknown Error";
response.json(status, {'errors': errors});

but this is not always the case, because the structure of the error can change, depending on the type of error. I know it's a broad question but I was wondering if you already faced this kind of problems.

Thanks!

Enum error

My field has property enum, I also defined validationMessages for that field, but the message return is not match with my expected:
'"in" validation rule failed for input: \'\'\nSpecifically, it threw an error. Details:\n undefined'

fallback locale if specific locale is not provided

your example were:

{
    "authentication.email.required": "Email is required",
    "authentication.email.email": "Provide valid email address",
    "authentication.email.unique": "Email address is already taken",
    "authentication.username.required": "Username is required",
    "authentication.username.string": "Username is must be a valid string",
    "authentication.birthday.required": "Birthday is required",
    "authentication.birthday.date": "Birthday is not a valid date"
}

but it would be more great if default error messages would be available. E.g.:

{
  "default.required": "#{fieldName} is required",
  "default.unique": "#{fieldName} is already taken"
}

At least it would be perfect if the hook would provide a default setup of error messages, and anyone could easily overwrite the default setup with his locales.

TypeError: request.getLocale is not a function

Hi there
When send request, got locale error,
how to turn off force locale checking?

file index.js

routes: {
            before: {
                'all /*': function grabLocale(request, response, next) {
                    //configure i18n current request locale
                    sails.config.i18n.requestLocale = request.getLocale(); //<-- error here

                    //continue
                    next();
                }
            }
        }

Think about alternative to sails.config.i18n.requestLocale

Using sails.config.i18n.requestLocale = request.getLocale(); is a bad idea!

It assumes that all the requests are processed serially and so, parallel requests will fail to get the correct locale!

https://github.com/lykmapipo/sails-hook-validation/blob/master/index.js#L73

    return {
        //intercent all request and current grab request locale
        routes: {
            before: {
                'all /*': function grabLocale(request, response, next) {
                    //configure i18n current request locale
                    sails.config.i18n.requestLocale = request.getLocale();

                    //continue
                    next();
                }
            }
        },

...

Use Field values in i18n translations

I think you can change your validateCustom.js to show field values on errors something like this:

var fieldValue = (typeof model.attributes[validationField][fieldError.rule] === 'undefined') ? '' : model.attributes[validationField][fieldError.rule];
var customMessage = sails.__({
                            phrase: phrase,
                            locale: locale
                        },fieldValue);

and then we can use something like this in translation files
"contact.name.minLength": "minimum length is %s .",

Sorry for my bad English

Does not work with sails-hook-autoreload

Hi,

I am trying to use sails-hook-validation with sails-hook-autoreload. But after code is changed, and sails-hook-autoreload reloads the controllers no validation-errors are returned (the errors array is null).
Should this work?

Access i18n from model validations

Hi

Thanks very much for this add-on , it was very much needed.

Could you telle me how to access i18n variables from the model validations ?

Thank you

Not working as expected.

Hello,

This looked like a good solution for my custom validation message needs, but unfortunately this is not working.

I am using sails 11

Below is my model:

module.exports = {

    attributes: {
        name: {
            type: "string",
            unique: true
        },
        email: {
            type: "email",
            unique: true
        },
        password: {
            type: "string"
        }
    },
    validationMessages: { //hand for i18n & l10n
        name: {
            unique: 'name is already taken'
        },
        email: {
            required: 'Email is required',
            email: 'Provide valid email address',
            unique: 'Email address is already taken'
        }
    }

}

Dont know if this interests you or not, but this is the sails generated error object which I got form console.log(error) at node_modules/sails-hook-validation/lib/create.js line no: 50, before the if(error.ValidationError).

{
    "error" : "E_VALIDATION",
    "status" : 400,
    "summary" : "2 attributes are invalid",
    "invalidAttributes" : {
        "name" : [{
                "value" : "hb",
                "rule" : "unique",
                "message" : "A record with that `name` already exists (`hb`)."
            }
        ],
        "email" : [{
                "value" : "[email protected]",
                "rule" : "unique",
                "message" : "A record with that `email` already exists (`[email protected]`)."
            }
        ]
    }
}

Since the above error object do not have the ValidationError property, It will not be going into the if statement.

Issues with override

Hi,

I'm not sure if it's a bug or me not doing the right thing. I haven't had much time looking for the root of my issue.

I have the latest version of sails 0.11.1, I couldn't make the override work with blueprint ( haven't tried without).

For my blueprint create, I managed to make it work by replacing line 51 of create.js.

Before:

 if (error.ValidationError) {
                        error.Errors =
                            validateCustom(model, error.ValidationError);
                    }

After:

if (error.ValidationError) {
                        error.invalidAttributes = 
                            _.merge(error.invalidAttributes, validateCustom(model, error.ValidationError));
                    }

Are you overriding error message or "annotating" them?

Issue on sails-hook-validation/lib/validateCustom.js:90

I just downloaded the code and follow your instructiosn and for some reason I'm gettingt he following error when running the create method:

/apps/sails/node_modules/sails-hook-validation/lib/validateCustom.js:90
customMessage = messages[validationField][fieldErro
^
TypeError: Cannot read property 'required' of undefined

Can enums be validated?

I have a field named status in my User model. Any way I can have validation for that field?

status: 
        {
            type:         "string",
            enum:         ['activating', 'activated'],
            defaultsTo:   'activating',
            required:     true
        },

Errors in error.invalidAttributes but error.Errors is undefined

My model looks liks this

module.exports = {
    types: {
        password: function(password){
            if(password != null){
                return password === this.confirm_password;
            }
            else{
                return true;
            }
        }
    },
    attributes: {
        id: {
            type: 'int',
            autoIncrement: true,
            primaryKey: true
        },
        email: {
            type: 'email',
        },
        password: {
            type: 'string',
            required: true,
            password: true
        },
        active: {
            type: 'boolean'
        },
        last_login_date: {
            type: 'datetime'
        }
    },
    validationMessages : {
        password: {
            password: 'Passwords do not match',
        },
        email: {
            email: 'testing',
        }
    },
};

In my controller I'm doing this

Admin.update({id: req.body.id}, saveData, function(err, result){                            
    console.log(err.invalidAttributes);
    console.log(err.Errors);                                
});

In my console the err.invalidAttributes has

{ password:
[ { rule: 'password',
message: '"password" validation rule failed for input: 'fasdf'' } ] }

while the err.Errors is undefined.

Am I missing something?
I ran npm install --save sails-hook-validation

My sails version is 0.11

throw errors in sails v1.0.0-37

sails> Page.create({name:'t'}).exec(console.log)Error (E_UNKNOWN) :: Encountered an unexpected error
at new WLError (/Users/dany/Projects/rocket-common-h5/node_modules/sails-hook-validation/node_modules/waterline/lib/waterline/error/WLError.js:26:15)
at Object.module.exports.patch (/Users/dany/Projects/rocket-common-h5/node_modules/sails-hook-validation/lib/WLValidationError.js:8:13)
at /Users/dany/Projects/rocket-common-h5/node_modules/sails-hook-validation/lib/create.js:66:48
at _.extend._WLModel (/Users/dany/Projects/rocket-common-h5/node_modules/waterline/lib/waterline/methods/create.js:155:20)
at parley (/Users/dany/Projects/rocket-common-h5/node_modules/parley/lib/parley.js:111:5)
at newConstructor.create (/Users/dany/Projects/rocket-common-h5/node_modules/waterline/lib/waterline/methods/create.js:130:10)
at newConstructor.create (/Users/dany/Projects/rocket-common-h5/node_modules/sails-hook-validation/lib/create.js:47:14)
at module.exports.Deferred.exec (/Users/dany/Projects/rocket-common-h5/node_modules/sails-hook-validation/node_modules/waterline/lib/waterline/query/deferred.js:477:16)
at repl:1:25
at ContextifyScript.Script.runInThisContext (vm.js:50:33)
at REPLServer.defaultEval (repl.js:239:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12)
at REPLServer.onLine (repl.js:440:10)
at emitOne (events.js:120:20)
at REPLServer.emit (events.js:210:7)
at REPLServer.Interface._onLine (readline.js:282:10)
at REPLServer.Interface._line (readline.js:631:8)
at REPLServer.Interface._ttyWrite (readline.js:911:14)
at REPLServer.self._ttyWrite (repl.js:509:7)
at ReadStream.onkeypress (readline.js:160:10)
at emitTwo (events.js:125:13)

is it the waterline's version? because the v1 uses a new one.

Use without i18n shows a locale warning

Hey, after installing the hook and adding the basic necessities(non i18n) into my model described in the readme, I am getting an error when creating a new user. Using sails 0.11.5 sails-hook-validation 0.4.5

Error

i18n:warn WARN: Locale en couldn't be read - check the context of the call to $__. Using en (default) as current locale +0ms. 

node_modules\sails\node_modules\i18n\i18n.js:503
      return locales[locale][singular];
                            ^
TypeError: Cannot read property 'user.email.unique' of undefined

my model:

attributes: {
  email: {
    type: 'email',
    required: true,
    unique: true
  }
},
validationMessages: {
  email: {
    required: 'An email is required.',
    email: 'Provide a valid email address.',
    unique: 'The email address entered is already being used.'
  }
}

bug in sails 0.12

I think you need change your readme code to this in sails 0.12

User
    .create({}, function(error, user) {
        var expect = require('expect');
        //you will expect the following
        //error to exist on error.Errors based on 
        //your custom validation messages

        expect(error.invalidAttributes.email).toExist;

        expect(error.invalidAttributes.email[0].message)
          .toEqual(User.validationMessages.email.email);

        expect(error.invalidAttributes.email[1].message)
          .toEqual(User.validationMessages.email.required);


        expect(error.invalidAttributes.username).toExist;
        expect(error.invalidAttributes.username[0].message)
          .toEqual(User.validationMessages.username.required);

        done();
      });

But it still does not work properly for me I think the problem of "expect", because the message "Object.assert [as default]" is displayed on the console

Errors on Sails 1.0 installations

Thanks for a great plugin!

With Sails 1.0, the plugin fails. These are the errors I have encountered so far:

  • sails.util._ is no longer available (lodash is no longer included in sails), even when specifying a lodash instance in the configuration file.
  • sails.__ is not a function - I do not know why this doesn't work, since it's still in the documentation

The first should be easily fixed by changing from the Sails built-in lodash to your own instance. Not sure about the second one though.

Unique validation does not work

Hey there,

I really like what you made! Also the code is really easy to read and well documented. Thanks for this!

The only thing which I couldn't get to work was unique validation.

Could it be that unique validation ist not checked in model.validate()???

see #1 for more information

Unable to show validation errors

So i have been following all these steps in order to show the errors but i came up with nothing. Even when i try to access error.Errors i get undefined. So just to make sure im using sails 0.11 i have already set up the validations messages in my user model (same as the example) and then in my controller i did this:

module.exports = {
create: function(req, res, next) {
    var userObj = {
       username: req.param('username'),
       email: req.param('email')
    }

User.create(userObj).exec(function(err, user) {
 if (err) {
      expect(err.Errors.email).to.exist; // Get undefined email error here

    expect(err.Errors.email[0].message)
        .to.equal(User.validationMessages.email.email);

    expect(err.Errors.email[1].message)
        .to.equal(User.validationMessages.email.required);


    expect(err.Errors.username).to.exist;
    expect(err.Errors.username[0].message)
        .to.equal(User.validationMessages.username.required);

    done();
    }
    if (user) {
        console.log("hi");
    }else{
    return res.json(404, {err: 'User not found.'});
    }
  });
},

date type validation customization doen't work

Hello,

i think that i cannot customize validation messages of attributes with type "date" with your module
(sails v0.11 updated and latest module code too),

in my model User i have one attribute set as:

birthday: {
type: 'date',
required: true,
unique: false
},

in validationMessages object i added:

birthday: {
required: 'Your birthday is required',
birthday: 'Birthday is not a valid date'
}

when i called the User.create function (in Controller), with a invalid date 'aaa' in attribute birthday,

User.create(data, function(error, user) { (...) });

it returns validation errors as expected, but error.Error is empty (empty object {})

if i retrieve invalidAttributes property from errors, i get the original validation error:

{ birthday:
[ { rule: 'date',
message: 'undefined should be a date (instead of "aaa", which is a string)' } ] }

am i doing something wrong or date type validation is not customized correctly with your module?

thanks in advance.

Unique not working with primary key

Hi, i set up attribute in model with:

ma_nhan_vien: {
            type: 'string',
            required:true,
            unique:true,
            maxLength:25,
            primaryKey: true,
            notContains:' '
            }

and validation messgae

        ma_nhan_vien: {
            required: 'Vui lòng nhập mã nhân viên',
            unique: 'Mã nhân viên đã có sẵn',
            maxLength:'Mã nhân viên không thể vượt quá 25 ký tự',
            notContains:'Mã nhân viên không thể chứa khoảng trắng'
        }

But it not return message

[{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"invalidAttributes": {
"PRIMARY": [
{
"value": "NV01",
"rule": "unique",
"message": "A record with that PRIMARY already exists (NV01)."
}
]
},
"message": "[Error (E_VALIDATION) 1 attribute is invalid] Details: { code: 'E_UNIQUE',\n invalidAttributes: { PRIMARY: [ [Object] ] },\n originalError: [Circular] }\n",
"stack": "Error (E_VALIDATION) :: 1 attribute is invalid\n at new WLError (D:\code\devme\stec_sctm_system\node_modules\sails-hook-validation\node_modules\waterline\lib\waterline\error\WLError.js:26:15)\n at Object.module.exports.patch (D:\code\devme\stec_sctm_system\node_modules\sails-hook-validation\lib\WLValidationError.js:8:13)\n at D:\code\devme\stec_sctm_system\node_modules\sails-hook-validation\lib\create.js:66:48\n at D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\query\dql\create.js:223:14\n at wrapper (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\lodash\index.js:3592:19)\n at applyInOriginalCtx (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\utils\normalize.js:421:80)\n at wrappedCallback (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\utils\normalize.js:335:16)\n at callback.error (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\switchback\lib\normalize.js:42:31)\n at _switch (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\switchback\lib\factory.js:56:28)\n at afterwards (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\adapter\dql.js:87:16)\n at wrapper (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\lodash\index.js:3592:19)\n at applyInOriginalCtx (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\utils\normalize.js:421:80)\n at wrappedCallback (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\waterline\lib\waterline\utils\normalize.js:335:16)\n at callback.error (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\switchback\lib\normalize.js:42:31)\n at _switch (D:\code\devme\stec_sctm_system\node_modules\sails-hook-orm\node_modules\switchback\lib\factory.js:56:28)\n at sendBackError (D:\code\devme\stec_sctm_system\node_modules\sails-mysql\lib\connections\spawn.js:97:11)\n at Object.module.exports.poolfully as releaseConnection\n at D:\code\devme\stec_sctm_system\node_modules\sails-mysql\lib\connections\spawn.js:90:37\n at Query._callback (D:\code\devme\stec_sctm_system\node_modules\sails-mysql\lib\adapter.js:395:27)\n at Query.Sequence.end (D:\code\devme\stec_sctm_system\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)\n at Query.ErrorPacket (D:\code\devme\stec_sctm_system\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Query.js:94:8)\n at Protocol._parsePacket (D:\code\devme\stec_sctm_system\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:280:23)"
}

](url)

Problem with npm 3

Hello.

When I try run sails app, I get next error:

error: Error: Cannot find module 'sails/node_modules/waterline/lib/waterline/query/deferred'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/user/projects/happsy/happsyphoto/node_modules/sails-hook-validation/lib/create.js:5:16)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/user/projects/happsy/happsyphoto/node_modules/sails-hook-validation/index.js:10:14)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

In npm 3 modules have flat structure and waterline module installed outside sails folder. I think you should include waterline module in your package.json like dependence.
In advance, thanks.
P.S. sorry for my bad english.

It's not working for me

Hello!

I'm trying to use this hook in order to translate my application, however, it's not working.

$ npm list sails
[email protected] /home/sfomin/mysite
└── [email protected]
// api/models/User.js
var _ = require('lodash');
var _super = require('sails-auth/api/models/User');
_.merge(exports, _super);
_.merge(exports, {
});
// api/controllers/AuthController.js

var _ = require('lodash');
var _super = require('sails-auth/api/controllers/AuthController');
var Promise = require('bluebird');
var redirectUrl = '/';

_.merge(exports, _super);
_.merge(exports, {

  // ...

  signUp: function signUpAction (req, res) {

    if (req.user) {
      return res.redirect(redirectUrl);
    }

    checkPost()
      .then(createUser)
      .then(redirect)
      .catch(showForm)
    ;


    function checkPost () {
      return ('POST' == req.method ? Promise.resolve() : Promise.reject());
    }

    function createUser () {
      return User
        .register(req.body)
      ;
    }

    function redirect () {
      res.redirect(redirectUrl);
      return Promise.resolve();
    }

    function showForm (err) {
      console.log(JSON.stringify(err));
      var context = {
        form: req.body,
        errors: (err && err.invalidAttributes ? err.invalidAttributes : [])
      };
      res.view('auth/sign-up', context);
    }

  }
});

As you can see I'm also using sails-auth in order to implement authentication.

config/locales/ru.json:

{
  "user.email.unique": "Указанный E-Mail уже занят"
}

I'm getting the standard error message instead of localized one.

// config/i18n.js
module.exports.i18n = {
  locales: ['en', 'ru'],
  defaultLocale: 'ru',
  updateFiles: true
};

Please advise, thanks!

Custom validation message does not work

When the attribute name and the column name is different, there is a bug that does not use a custom message.

I think the problem is part of the following.
https://github.com/lykmapipo/sails-hook-validation/blob/master/lib/validateCustom.js#L45

model

// User.js
module.exports = {
  tableName: 'users',
  attributes: {
    id: {
      columnName: 'id',
      type: 'integer',
      autoIncrement: true,
      primaryKey: true
    },
    name: {
      columnName: 'user_name', // attribute name !== column name
      type: 'string',
      required: true
    }
  },
  validationMessages: {
    name: {
      string: 'My custom message1',
      required: 'My custom message2'
    }
  }
};

code

User.create({ name: null }).then(function() {

}).catch(function(err) {
  console.log(err.Errors['name']); // undefined!!, I expect the My custom message1, My custom message2
});

error.Errors is empty using associations

https://github.com/lykmapipo/sails-hook-validation/blob/master/lib/validateCustom.js#L100
When i output newMessage i see the proper message but error.Error is empty. (rather than undefined).

It seems that when validating on an association it will trigger the (in my case) lib/create.js twice.
The first call will define the error because the association has an error.
The 2e call will return an empty object because it will check the orignal model which has no errors.

Using Sails 0.11.0 and version 4.0

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.