Added general phone number validator.

This commit is contained in:
Martin Donnelly 2016-03-15 17:34:51 +00:00
parent 9029aee061
commit 78f09a300c
2 changed files with 100 additions and 0 deletions

View File

@ -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;

31
test/phone-validator.js Normal file
View File

@ -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();
});
});