express-route-model

Input model binding for express routing

npm install express-route-model
2 downloads in the last week
10 downloads in the last month

express-route-model

Input model binding for express routing.

npm install express-route-model

This concept was originally derived from MVC models in .NET framework, and mongoose model validations. The point is to skip all the repetitive validation code in your routes and get straight to the business logic.

The check and freshen functions pull largely from the excellent node-validator project.

Quick Example

So let's say we have a web form like this:

<form action='/save' method='post'>
    <input type='text' name='name[first]'/>
    <input type='text' name='name[last]'/>
    <input type='text' name='email'/>
    <button type='submit'>Save</button>
</form>

Now, let's validate this form server-side:

RouteModel = require('express-route-model');

/*
    Example Input:
    --------------
    email = "TylerShaddix@gmail.com"
    name[first] = "Tyler  "
    name[last] = "Shaddix"
*/

saveModel = new RouteModel({
    body : {
        name : {
            first : {
                trim : true
            },
            last : {
                trim : true
            }
        },
        email :{
            isEmail : true,
            lowercase : true
        }
    }
});

app.post('/save', saveModel.expose, function(req, res, next){

    req.model.isValid // true

    req.model.errors // []

    req.model.body.email // tylershaddix@gmail.com

    req.model.body.name // { first : 'Tyler', last : 'Shaddix' }

});

Wait? That's it?

Yep.

Checks

A check will hold an assertion and return a true or false value. If the value returned does not match provided value, then the model will be invalidated.

check: value - explanation

  • is: RegExp - Invalidate if does not match.
  • not: RegExp - Invalidate if match.
  • isEmail: Boolean
  • isUrl: Boolean
  • isIP: Boolean
  • isIPv4: Boolean
  • isIPv6: Boolean
  • isAlpha: Boolean
  • isAlphanumeric: Boolean
  • isNumeric: Boolean
  • isHexadecimal: Boolean
  • isHexColor: Boolean
  • isInt: Boolean
  • isLowercase: Boolean
  • isUppercase: Boolean
  • isDecimal: Boolean
  • isFloat: Boolean - Same as isDecimal.
  • notNull: Boolean
  • isNull: Boolean
  • notEmpty: Boolean
  • equals: String
  • contains: String
  • notContains: String
  • minLength: Number
  • maxLength: Number
  • isUUID: Boolean
  • isUUIDv3: Boolean
  • isUUIDv4: Boolean
  • isDate: Boolean
  • isAfter: Date
  • isBefore: Date
  • isIn: Array or String
  • notIn: Array or String
  • max: Number
  • min: Number
  • isCreditCard: Boolean

Freshens

A freshen will manipulate the parameter slightly.

  • lowercase: Boolean
  • trim: Boolean
  • ltrim: Boolean
  • rtrim: Boolean
  • ifNull: String
  • toFloat: Boolean
  • toInt: Boolean
  • toBoolean: Boolean
  • toBooleanStrict: Boolean
  • entityDecode: Boolean
  • entityEncode: Boolean
  • escape: Boolean
  • xss: Boolean
  • xssImage: Boolean

Extending

Extending the check and freshen functions is straight forward. The check function can include a second argument of the model value, such as with a regex matching.


RouteModel = require('../');

Check = RouteModel.Check
Freshen = RouteModel.Freshen

// checks whether value = 'monkey'
Check.prototype.isMonkey = function(val){
    return val === 'monkey';
};

// adds plus to end of string
Freshen.prototype.addPlus = function(val){
    return val + "+";
};

myModel = new RouteModel({
    body : {
        animal : {
            isMonkey : true
        },
        bloodType : {
            addPlus : true
        }
    }
});

Custom Error Messages

To include a custom error message, pass an object instead of a value for an model's check which includes the expected value and a message.


myModel = new RouteModel({
    body : {
        email: {
            isEmail : {
                value : true,
                message : "That's a bad email!"
            }
        }
    }
});

License

(The MIT License)

Copyright (c) 2011 Tyler Shaddix tylershaddix@gmail.com

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.

npm loves you