Ensuring numbers only with Svelte input validation, letters slip through my prevention efforts

I'm stumped on what is causing this issue. The input field is still displaying letters when it shouldn't be.

<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>

Check out the REPL link for more details.

Answer №1

REPL

If you need to notify the user about input validation... use the code snippet 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} />

For input validation without displaying a warning to the user... use the following code

<script>
  let value = "";

  $: value = value.replace(/[^0-9]/g, '')
</script>
<input bind:value />

Answer №2

One simple solution is:

else {
    e.target.value = oldValue;
}

Answer №3

After gathering inspiration from various sources, I found a solution that worked for me.

This approach involves:

  • Converting the input value to a number
  • Filtering out any characters that would prevent the value from being a number
  • Adding an additional pattern attribute to assist with 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 {
    // revert to previous value
    target.value = value.toString();
  }
}
<input
  type="text"
  inputmode="numeric"
  pattern="[0-9.]*"
  {value}
  on:input|preventDefault={updateValue}
/>

Answer №4

Change the input field to a numeric type for better user experience.

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

Try out this REPL link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for Nextjs routing catchAll to coexist with a slug folder within a route?

When converting my pages to ISR, I encountered an issue with handling params and dynamic routes. One example is where article/?pageNumber=2 needs to be rewritten as article/2 in middleware for improved performance. However, this change in routing structure ...

What is the best way to implement React.memo or useMemo and ensure semantic guarantees?

According to the documentation provided for useMemo: While useMemo can improve performance, it should not be solely relied upon for semantic guarantees. React may choose to recalculate previously memoized values in the future, such as to free up memo ...

Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post d ...

Converting large JSON data (approximately 100MB) into an Excel file using JavaScript

As a beginner in the realm of REST technology, I find myself navigating through a JSON response received from a server and showcasing the data on the client side. Currently, I am faced with handling approximately 22MB of JSON data that needs to be exporte ...

How to Use Jquery to Calculate the Total Number of HTML Elements Generated Dynam

Currently, I am trying to count the number of inputs on the document that have a value. The code works fine until I dynamically add more inputs. At that point, I am unable to retrieve their values. Here is an example: <input id="participant-1"/> &l ...

Typescript generates a warning when utilizing JSON objects in conjunction with data types

Attempting to access the attributes of a JSON object within a hook using bracket notation. Although it seems to be functioning correctly, TypeScript continues to throw this warning: Property 'github' does not exist on type 'PropertyValues& ...

The download window is malfunctioning and unable to save the file

I'm currently developing an ASP.NET Web Form application with a specific requirement: to display a popup box for downloading an Excel file when the user clicks on a link. This link is located within a popup page, not on the main ASPX page. Here' ...

Encountering a mysterious error while attempting to access and modify a value stored in a useState hook using the keydown

I've been attempting to create a simple animation on canvas using React.js, but I'm facing an issue with integrating my Keydown function with my useState. It seems that my useState value is not being defined properly, preventing me from changing ...

The challenge of vertically aligning text in a dynamically generated div

Currently, I am in the process of developing a straightforward application that allows for the dynamic addition of students and teachers. I am dynamically adding divs with a click function. To these dynamically created divs, I have assigned the class "us ...

Discovering the quantity of arguments passed into a constructor in Node.js

In my Node.js code, I have a constructor that looks like this: function Tree() { //Redirect to other functions depending on the number of arguments passed. } I then created instances of objects like so: var theTree = new Tree('Redwood'); var ...

Attempted to load Angular multiple times

I recently developed an app using the Yeoman scaffolded app (specifically, the Angular Fullstack generator). While grunt serve works perfectly fine, I encountered a problem when running grunt build which results in the distribution locking up memory. This ...

Error message encountered when attempting to rotate an object in three.js: "Object is undefined"

Experiencing an "Undefined Object" error while attempting to rotate an object using three.js. Here is a snippet of the code in question: var object; function render() { renderer.render(scene, camera); } function animate() { object.rotation.x + ...

(Build an Angular, TypeScript Application) Develop a new function using a string that includes an if statement without using the eval function

Is it possible to create a new function from a string that includes an if condition? The actual string will be provided externally, but for the sake of this example, everything is hardcoded. let f1: number = 1; let f2: number = 0; let condition: string ...

What is the best way to monitor different selections to keep track of their state?

In a certain scenario, a user is presented with three options: They can select the body_type of a car, the car_year it was manufactured, or the car_make. Initially, there is a state called carJson which contains a list of cars. "2": { " ...

Tips for displaying specific HTML elements in AngularJS using ng-repeat and ng-if

I am working with some bootstrap HTML code that includes an ng-repeat function. <div class="row"> <div class="col-lg-4" ng-repeat="p in persons"> <img class="img-circle" src="images/{{ p.image }}" width="140" height="140"> < ...

JavaScript: comparison between browser and native support for setTimeout and setInterval

In the world of programming, JavaScript is but a language that boasts various different implementations. One such implementation is the renowned V8 engine, which finds utility in both Google Chrome and Node.js. It's important to note that support for ...

Sending a PHP error back in response to an Ajax call

My PHP script needs to be called with AJAX, but I keep getting an error message that says "Error:email=my_email&password=myPassword". Check out the PHP script below: <?php session_start(); require "db_config.php"; if ($_SERVER["request_method"] ...

How come React.js is not displaying images from local URLs?

In my React application, there is a form where users can submit an image file. To store the path of the submitted image locally for browser access, I utilized URL.createObjectURL to generate a URL for the file. Here is the code snippet: handleImageChange(e ...

Utilizing HTML/CSS with React/Bootstrap: A Comprehensive Guide

Looking for help with integrating HTML/CSS code into React/Bootstrap? I need assistance with coding in React using Bootstrap. How do I effectively use components and props? Even after installing bootstrap, I am encountering errors. Is it possible to dire ...

Ways to simulate a constant that acts as a dependency for the service being examined?

I'm currently experimenting with a file named connect-key.js. It relies on a dependency called keyvault-emulator. Content of File #1: // connect-key.js file const { save, retrieve, init } = require('./keyvault-emulator') .... .... .... // ...