diff --git a/src/index.js b/src/index.js index 5e2cd78a7..709c0218b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,4 @@ +import isUsername from './lib/isUsername'; import toDate from './lib/toDate'; import toFloat from './lib/toFloat'; import toInt from './lib/toInt'; @@ -246,6 +247,8 @@ const validator = { isLicensePlate, isVAT, ibanLocales, + isUsername, + }; export default validator; diff --git a/src/lib/isNumeric.js b/src/lib/isNumeric.js index 4cc7ea5b3..01a72e0af 100644 --- a/src/lib/isNumeric.js +++ b/src/lib/isNumeric.js @@ -5,6 +5,11 @@ const numericNoSymbols = /^[0-9]+$/; export default function isNumeric(str, options) { assertString(str); + + if (str === '' || str.length === 0) { + return false; + } + if (options && options.no_symbols) { return numericNoSymbols.test(str); } diff --git a/src/lib/isUsername.js b/src/lib/isUsername.js new file mode 100644 index 000000000..eb770be53 --- /dev/null +++ b/src/lib/isUsername.js @@ -0,0 +1,15 @@ +import assertString from './util/assertString'; + +export default function isUsername(str) { + assertString(str); + if (str.length < 3 || str.length > 15) { + return false; + } + for (let i = 0; i { + it('should return true for valid usernames', () => { + assert.strictEqual(isUsername('roghana'), true); + assert.strictEqual(isUsername('user123'), true); + }); + + it('should return false if username length is less than 3', () => { + assert.strictEqual(isUsername('ab'), false); + }); + + it('should return false if username length is more than 15', () => { + assert.strictEqual(isUsername('verylongusername123'), false); + }); + + it('should return false if username contains restricted special characters', () => { + assert.strictEqual(isUsername('user@123'), false); + assert.strictEqual(isUsername('hello#'), false); + assert.strictEqual(isUsername('$money'), false); + }); +});