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 16, 2024
1 parent 2ffcfb1 commit de8a93d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
13 changes: 13 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 = 189;

export interface AmountInputArgs {
/**
Expand Down Expand Up @@ -130,9 +131,21 @@ export default class AmountInput extends Component<AmountInputSignature> {

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

if (event.keyCode === KEY_CODE_E) {
event.preventDefault();
return false;
} else if (isMinus) {
const { target } = event;
if (
target instanceof HTMLInputElement &&
target.value !== '' &&
target.selectionStart !== 0
) {
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,28 @@ module('Integration | Component | amount-input', function (hooks) {
});
});
});

test('should not 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)}}
/>
`);

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

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

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

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

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

0 comments on commit de8a93d

Please sign in to comment.