diff --git a/md-validator.js b/md-validator.js index 132deec..04a9a5b 100644 --- a/md-validator.js +++ b/md-validator.js @@ -263,6 +263,75 @@ var VALIDATE = new function() { // Telephone number seems to be valid - return the stripped telehone number return telnum; }; + + this.validatePhone = function(params) { + "use strict"; + + var f = params.f; + var uk = params.uk || false; + var flag = params.flag; + var v = params.number; + var required = params.req || false; + var itrx, iflag = true; + + var onlyDigits = function(inval) { + + var ch, ws = '', allowed = "0123456789+"; + + for (var t = 0; t <= inval.length; t++) { + ch = inval.charAt(t); + if (allowed.indexOf(ch) != -1) ws = ws + ch; + } + + return ws; + }; + + if (v.length == 0 && required == true) return ''; + + if (v.length > 0) { + var internationalTest1 = /((\+|00)([0-9]{2,3}))(\(0\)|0)([1-9][0-9]{9})$/i; + var internationalTest2 = /((\+|00)([0-9]{2,3}))([1-9][0-9]{9})$/i; + + // tidy up international format numbers. + if (internationalTest1.test(v) == true) { + itrx = internationalTest1.exec(v); + v = "00" + itrx[3] + itrx[5]; + } + else if (internationalTest2.test(v) == true) { + itrx = internationalTest2.exec(v); + v = "00" + itrx[3] + itrx[4]; + } + + // strip invalid characters + v = onlyDigits(v); + if (v.length < 8) return ''; + + // only do this if it hasn't already failed + + if (uk) { + // perform uk specific tests + // de-internationalise the number + if (v.substr(0, 3) == "+44") v = "0" + v.substr(3, v.length); + if (v.substr(0, 4) == "0044") v = "0" + v.substr(4, v.length); + var pcv = this.checkUKTelephone(v); + if (pcv === false) return ''; + if (pcv != false) v = pcv; + } + else { + // assume foreign + + if (!(v.charAt(0) == "+" || v.substr(0, 2) == "00")) { + // not right? + + return ''; + } + + } + } + + return v; + }; + }; module.exports = VALIDATE; diff --git a/test/phone-validator.js b/test/phone-validator.js new file mode 100644 index 0000000..9991ce4 --- /dev/null +++ b/test/phone-validator.js @@ -0,0 +1,31 @@ +"use strict"; +var $V = require('../md-validator'); + +var assert = require('assert'); + +describe('Phone Validator', function() { + it('should not validate an empty phone number', function(done) { + assert.equal($V.validatePhone({number: ''}), ''); + done(); + }); + + it('should validate an normal uk number', function(done) { + assert.equal($V.validatePhone({number: '01389 602001', uk: true}), + '01389602001'); + done(); + }); + + it('should validate an normal prefixed uk number', function(done) { + assert.equal($V.validatePhone({number: '+441389 602002', uk: true}), + '01389602002'); + done(); + }); + + it('should validate a bracketted uk number', function(done) { + assert.equal($V.validatePhone({number: '(0)1389 602003', uk: true}), + '01389602003'); + done(); + }); + + +});