Skip to content

Commit

Permalink
fix(input): added input validation to throw descriptive errors
Browse files Browse the repository at this point in the history
Fix #40
  • Loading branch information
grantila committed Aug 27, 2019
1 parent 578f21b commit bc8f1de
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,11 @@ function PhoneNumber( phoneNumber, regionCode )

let parsed;

if ( !isInternal && typeof phoneNumber !== 'string' )
throw new Error( "Invalid phone number, expected a string" );
if ( !isInternal && regionCode != null && typeof regionCode !== 'string' )
throw new Error( "Invalid region code, expected a string" );

if ( !isInternal )
{
if ( regionCode && ( phoneNumber.charAt( 0 ) === '+' ) )
Expand Down
19 changes: 19 additions & 0 deletions test.in/awesome-phonenumber/should-compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,23 @@ describe( 'errors', function( ) {
expect( pn.isPossible( ) ).to.be.false;
expect( pn.toJSON( ).possibility ).to.equal( 'too-short' );
} );

it( 'should handle invalid phone number', function( ) {
const failure = ( arg: any ) => ( ) => new PhoneNumber( arg );

expect( failure( null ) ).to.throw( "Invalid phone number" );
expect( failure( { } ) ).to.throw( "Invalid phone number" );
expect( failure( [ ] ) ).to.throw( "Invalid phone number" );
expect( failure( 5 ) ).to.throw( "Invalid phone number" );
expect( failure( true ) ).to.throw( "Invalid phone number" );
} );

it( 'should handle invalid phone number', function( ) {
const failure = ( arg: any ) => ( ) => new PhoneNumber( '987654321', arg );

expect( failure( { } ) ).to.throw( "Invalid region code" );
expect( failure( [ ] ) ).to.throw( "Invalid region code" );
expect( failure( 5 ) ).to.throw( "Invalid region code" );
expect( failure( true ) ).to.throw( "Invalid region code" );
} );
} );

0 comments on commit bc8f1de

Please sign in to comment.