Skip to content

Instantly share code, notes, and snippets.

@johnnncodes
Last active January 1, 2016 17:19
Show Gist options
  • Save johnnncodes/8176318 to your computer and use it in GitHub Desktop.
Save johnnncodes/8176318 to your computer and use it in GitHub Desktop.

Revisions

  1. John Kevin M. Basco revised this gist Dec 30, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    make a module in node_modules named 'my-validation-utils'. create a index.js file there. and put the following content there:
    // make a module in node_modules named 'my-validation-utils'. create a index.js file there. and put the following content there:

    var user = {
    email:{
    @@ -40,7 +40,7 @@ module.exports = function(model,validationError){
    return validationError;
    };

    Now in your controller do the following:
    // Now in your controller do the following:

    User.create(user).done(function (error, user) {
    if (error) {
  2. John Kevin M. Basco created this gist Dec 30, 2013.
    57 changes: 57 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    make a module in node_modules named 'my-validation-utils'. create a index.js file there. and put the following content there:

    var user = {
    email:{
    required:'Email Required',
    email:'Should be an email'
    },
    name:{
    required:'name required'
    }

    };

    var product={
    name:{
    required:'Product name is required'
    }
    }

    var validationMessages = {
    user:user,
    product:product
    };

    /**
    * This function expects the name of the model and error.validationError
    * and puts the user defined messages in error.validationError
    */
    module.exports = function(model,validationError){
    var messages = validationMessages[model];
    for(key in messages){
    var element = messages[key];
    if(validationError[key]){
    for(i in validationError[key]){
    var err = validationError[key][i];
    err.message = element[err.rule];
    }
    }
    }
    return validationError;
    };

    Now in your controller do the following:

    User.create(user).done(function (error, user) {
    if (error) {
    if (error.ValidationError) {
    var validator = require('my-validation-utils');
    var errors = validator('user',error.ValidationError);// puts the messages for model user
    //now errors contains the validationErrors with user defined messages
    }

    } else {
    //user is saved
    }
    });