Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 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,8 @@ import './amount-input.css';
const KEY_CODE_E = 69;
const KEY_CODE_FULLSTOP = 190;
const KEY_CODE_COMMA = 188;
const KEY_CODE_MINUS = 189;
const KEY_MINUS = '-';

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

/**
* Specifies if the input value should be restricted to integer only
*/
integerOnly?: boolean;

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

/**
* Specifies if the input value should be restricted to integer only
*/
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 @@ -130,9 +144,14 @@ export default class AmountInput extends Component<AmountInputSignature> {

@action
onKeyDown(event: KeyboardEvent): boolean {
const isMinus = event.keyCode === KEY_CODE_MINUS || event.key === KEY_MINUS;

if (event.keyCode === KEY_CODE_E) {
event.preventDefault();
return false;
} else if (this.integerOnly && isMinus) {
event.preventDefault();
return false;
} else if (
this.numberOfDecimal === 0 &&
[KEY_CODE_FULLSTOP, KEY_CODE_COMMA].includes(event.keyCode)
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,45 @@ module('Integration | Component | amount-input', function (hooks) {
});
});
});

module('integer 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)}}
@integerOnly={{true}}
/>
`);

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

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

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