Skip to content

Commit

Permalink
feat: prevent minus sign typing
Browse files Browse the repository at this point in the history
  • Loading branch information
AntoineMoues committed Apr 11, 2024
1 parent 2ffcfb1 commit 4d8f73c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
17 changes: 17 additions & 0 deletions ember-amount-input/src/components/amount-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import './amount-input.css';
const KEY_CODE_E = 69;
const KEY_CODE_FULLSTOP = 190;
const KEY_CODE_COMMA = 188;
const KEY_CODE_MINUS = '-';

export interface AmountInputArgs {
/**
Expand All @@ -27,6 +28,11 @@ export interface AmountInputArgs {
*/
inputId?: string;

/**
* Specifies if value should be only be integer
*/
integerOnly?: boolean;

/**
* Specifies the minimum value for the input field
*/
Expand Down Expand Up @@ -102,6 +108,14 @@ export default class AmountInput extends Component<AmountInputSignature> {
return this.argOrDefault('inputId', 'amount-input');
}

/**
* Specifies if value should be only be integer
* Defaults to false
*/
get integerOnly(): boolean {
return this.argOrDefault('integerOnly', false);
}

/**
* Specifies the number of decimals to use for the amount value.
* Can be >= 0.
Expand Down Expand Up @@ -133,6 +147,9 @@ export default class AmountInput extends Component<AmountInputSignature> {
if (event.keyCode === KEY_CODE_E) {
event.preventDefault();
return false;
} else if (this.integerOnly && event.key === KEY_CODE_MINUS) {
event.preventDefault();
return false;
} else if (
this.numberOfDecimal === 0 &&
[KEY_CODE_FULLSTOP, KEY_CODE_COMMA].includes(event.keyCode)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,45 @@ module('Integration | Component | amount-input', function (hooks) {
});
});
});

module('positive only values', function () {
test('should not prevent negative values', async function (this: TestContext, assert) {
this.value = null as unknown as number;

await render<TestContext>(hbs`
<AmountInput
@numberOfDecimal={{0}}
@value={{this.value}}
@update={{fn (mut this.value)}}
/>
`);

assert.dom('input').hasValue('');

await fillIn('input', '-1000');
await blur('input');

assert.dom('input').hasValue('-1000');
});

test('should prevent negative values', async function (this: TestContext, assert) {
this.value = 1;

await render<TestContext>(hbs`
<AmountInput
@numberOfDecimal={{0}}
@value={{this.value}}
@update={{fn (mut this.value)}}
@positiveOnly={{true}}
/>
`);

assert.dom('input').hasValue('1');

await typeIn('input', '-1000');
await blur('input');

assert.dom('input').hasValue('1000');
});
});
});

0 comments on commit 4d8f73c

Please sign in to comment.