Sir Rubberduck
Sir Rubberduck

Reputation: 2292

Svelte input number validation. I can't prevent the input of letters

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

Answers (4)

parker_codes
parker_codes

Reputation: 3397

Here's what worked for me, taking inspiration from some of the other answers.

This:

  • coerces the value to a number
  • prevents any characters that make the value not result in a number
  • have an extra pattern on the input to assist form submission
export 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

Brandon
Brandon

Reputation: 151

Set the input's type to "number".

<input
    type='number'
    bind:value
    on:input|preventDefault={handleInput}
/>

REPL

Upvotes: -1

Marcques Mouton
Marcques Mouton

Reputation: 21

REPL

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

Jesper
Jesper

Reputation: 1096

you could just do this:

else {
    e.target.value = oldValue;
}

Upvotes: 1

Related Questions