Reputation: 2292
I am not sure what I'm doing wrong. Letters are still being shown in the input.
<script>
let value = "";
function isNumber(value) {
return !isNaN(value);
}
function handleInput(e) {
let oldValue = value;
let newValue = e.target.value;
console.log(oldValue, newValue, "isNumber", isNumber(newValue));
if (isNumber(newValue) && newValue.length < 17) {
value = newValue;
} else {
value = oldValue;
}
}
</script>
<div class="container">
<input
{value}
on:input|preventDefault={handleInput}
/>
</div>
Here's the REPL as well.
Upvotes: 2
Views: 3662
Reputation: 3397
Here's what worked for me, taking inspiration from some of the other answers.
This:
pattern
on the input to assist form submissionexport let value: number;
function updateValue(e: Event): void {
const target = e.target as HTMLInputElement;
const newValue = Number(target.value);
if (!isNaN(newValue)) {
value = newValue;
} else {
// reset to old value
target.value = value.toString();
}
}
<input
type="text"
inputmode="numeric"
pattern="[0-9.]*"
{value}
on:input|preventDefault={updateValue}
/>
Upvotes: 0
Reputation: 151
Set the input's type to "number".
<input
type='number'
bind:value
on:input|preventDefault={handleInput}
/>
Upvotes: -1
Reputation: 21
IF you want to warn the USER on input... use below
<script>
let value = "";
// Check if user input is number
const onKeyPress = e => {
if (!isFinite(e.key)) {
alert('Not A number')
}
};
$: value = value.replace(/[^0-9]/g, '')
</script>
<input bind:value on:keypress={onKeyPress} />
and without warning the user.. use below
<script>
let value = "";
$: value = value.replace(/[^0-9]/g, '')
</script>
<input bind:value />
Upvotes: 2