diff --git a/README.md b/README.md index aa88fd2..a30f374 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,10 @@ Tests if the value is a valid hash. ### Integer Tests if the value is an integer. +#### Arguments +- `allowString` (optional) - whether the assert accepts string inputs or not. +- `unsigned` (optional) - whether the assert should consider only unsigned values or not. + ### InternationalBankAccountNumber (*IBAN*) Tests if the value is a valid International Bank Account Number (_IBAN_) as defined in the [13616-1](http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=41031) standard. diff --git a/src/asserts/integer-assert.js b/src/asserts/integer-assert.js index ae6c095..52e535b 100644 --- a/src/asserts/integer-assert.js +++ b/src/asserts/integer-assert.js @@ -9,13 +9,16 @@ import { Validator, Violation } from 'validator.js'; * Int regex. */ -const int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; +const int = { + signed: /^(?:[-+]?(?:0|[1-9][0-9]*))$/, + unsigned: /^(?:\d+)$/ +}; /** * Export `IntegerAssert`. */ -export default function integerAssert() { +export default function integerAssert({ allowString = false, unsigned = false } = {}) { /** * Class name. */ @@ -27,11 +30,15 @@ export default function integerAssert() { */ this.validate = value => { - if (typeof value !== 'number') { + if (typeof value !== 'number' && !allowString) { throw new Violation(this, value, { value: Validator.errorCode.must_be_a_number }); } - if (int.test(value) !== true) { + if (unsigned && int.unsigned.test(value) !== true) { + throw new Violation(this, value); + } + + if (int.signed.test(value) !== true) { throw new Violation(this, value); } diff --git a/test/asserts/integer-assert_test.js b/test/asserts/integer-assert_test.js index a0fdb4e..b141560 100644 --- a/test/asserts/integer-assert_test.js +++ b/test/asserts/integer-assert_test.js @@ -44,7 +44,31 @@ describe('IntegerAssert', () => { } }); + it('should throw an error if strings are allowed but input is not valid', () => { + try { + new Assert().Integer({ allowString: true }).validate(' 1'); + + should.fail(); + } catch (e) { + e.show().assert.should.equal('Integer'); + } + }); + + it('should throw an error if only unsigned integers are allowed but input is not valid', () => { + try { + new Assert().Integer({ unsigned: true }).validate(-1); + + should.fail(); + } catch (e) { + e.show().assert.should.equal('Integer'); + } + }); + + it('should accept an unsigned integer as a string if strings are allowed', () => { + new Assert().Integer({ allowString: true, unsigned: true }).validate('1'); + }); + it('should accept an integer', () => { - new Assert().Integer().validate(1); + new Assert().Integer().validate(+1); }); });