Skip to content

Commit 822fd99

Browse files
committed
feat: prevent minus sign typing
1 parent 2ffcfb1 commit 822fd99

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

ember-amount-input/src/components/amount-input.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import './amount-input.css';
55
const KEY_CODE_E = 69;
66
const KEY_CODE_FULLSTOP = 190;
77
const KEY_CODE_COMMA = 188;
8+
const KEY_CODE_MINUS = 189;
89

910
export interface AmountInputArgs {
1011
/**
@@ -130,9 +131,21 @@ export default class AmountInput extends Component<AmountInputSignature> {
130131

131132
@action
132133
onKeyDown(event: KeyboardEvent): boolean {
134+
const isMinus = event.keyCode === KEY_CODE_MINUS || event.key === '-';
135+
133136
if (event.keyCode === KEY_CODE_E) {
134137
event.preventDefault();
135138
return false;
139+
} else if (isMinus) {
140+
const { target } = event;
141+
if (
142+
target instanceof HTMLInputElement &&
143+
target.value !== '' &&
144+
target.selectionStart !== 0
145+
) {
146+
event.preventDefault();
147+
return false;
148+
}
136149
} else if (
137150
this.numberOfDecimal === 0 &&
138151
[KEY_CODE_FULLSTOP, KEY_CODE_COMMA].includes(event.keyCode)

test-app/tests/integration/components/amount-input/component-test.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,4 +222,38 @@ module('Integration | Component | amount-input', function (hooks) {
222222
});
223223
});
224224
});
225+
226+
test('should not prevent negative values', async function (this: TestContext, assert) {
227+
this.value = 1;
228+
229+
await render<TestContext>(hbs`
230+
<AmountInput
231+
@numberOfDecimal={{0}}
232+
@value={{this.value}}
233+
@update={{fn (mut this.value)}}
234+
/>
235+
`);
236+
237+
assert.dom('input').hasValue('1');
238+
239+
await typeIn('input', '.');
240+
await blur('input');
241+
242+
assert.dom('input').hasValue('');
243+
244+
await typeIn('input', '-1000');
245+
await blur('input');
246+
247+
assert.dom('input').hasValue('-1000');
248+
249+
await typeIn('input', '.');
250+
await blur('input');
251+
252+
assert.dom('input').hasValue('');
253+
254+
await typeIn('input', '1000-');
255+
await blur('input');
256+
257+
assert.dom('input').hasValue('1000');
258+
});
225259
});

0 commit comments

Comments
 (0)