diff --git a/README.md b/README.md index 76d37ff..bee51e5 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ mongoose-types - Useful types and type plugins for Mongoose - Email - Url +- IPv4 Addresses ### Plugins include: @@ -53,6 +54,14 @@ Once you are setup, you can begin to use the new types. , referer: Url }); +#### IPv4 Addresses + + var IPv4 = mongoose.SchemaTypes.IPv4; + var ConnectionSchema = new Schema({ + sender : IPv4 + , recipient : IPv4 + }); + ### Using the plugins #### The `useTimestamps` plugin diff --git a/lib/types/ipv4.js b/lib/types/ipv4.js new file mode 100644 index 0000000..f23d0f3 --- /dev/null +++ b/lib/types/ipv4.js @@ -0,0 +1,20 @@ +var mongoose = require('mongoose') + +module.exports.loadType = function (mongoose) { + var SchemaTypes = mongoose.SchemaTypes; + +function IPv4 (path, options) { + SchemaTypes.String.call(this, path, options); + function validateIPv4(val) { + return /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gm.test(val); + } + this.validate(validateIPv4, 'IPv4 Address is invalid'); +} + IPv4.prototype.__proto__ = SchemaTypes.String.prototype; + IPv4.prototype.cast = function (val) { + return val.toLowerCase(); + }; + SchemaTypes.IPv4 = IPv4; + mongoose.Types.IPv4 = String; +}; +