skip to Main Content

I need an input in React that only write able -99 to 99 is there a way to achieve this?

i’ve tried on key down, but it brokes when you try to write double dashes for example;
it works perfectly when you try to write -45 or something.but when you add double dashes then it brokes it becomes writeable anything for example –9909349

also in this function i can write but i shouldn’t: 1-9034- etc.

only acceptable: -99 to 99

code:

const validateInput = (e) => {
    const currentValue = e.target.value
    const newValue = currentValue + e.key

    if (e.key === 'ArrowRight' || e.key === 'ArrowLeft' || e.key === 'Backspace') {
      return
    }

    if (e.key === '-' && currentValue === '') {
      return
    }

    if (newValue.replace(/0/g, '').length === 0) {
      e.preventDefault()
      return
    }

    if (parseInt(newValue) >= -99 && parseInt(newValue) <= 99) {
      return
    }

    e.preventDefault()
  }

2

Answers


  1. The min and max attributes in the <input> tag with type="number" are used to set the range of acceptable values, but they don’t prevent the user from manually entering values outside that range.

    You can use this logic to restrict the value between -99 to 99.

    function validateInput() {
      var input = document.getElementById('numInput');
      var value = input.value;
    
      var parsedValue = parseInt(value);
    
      if (isNaN(parsedValue) || parsedValue < -99 || parsedValue > 99) {
        input.value = Math.max(-99, Math.min(99, parsedValue || 0));
      }
    }
    <input type="number" id="numInput" oninput="validateInput()" />

    Or you can validate onblur for better UX. It will validate the input and reset it to the nearest valid value only after the user has finished editing

    function validateInput() {
      var input = document.getElementById('numInput');
      var value = input.value;
    
      var parsedValue = parseInt(value);
    
      if (isNaN(parsedValue) || parsedValue < -99 || parsedValue > 99) {
        input.value = Math.max(-99, Math.min(99, parsedValue || 0));
      }
    }
    <input type="number" id="numInput" onblur="validateInput()" />
    Login or Signup to reply.
  2. In a React application, you can create a component that allows users to input values between -99 and 99 and validate their input. Here’s an example of how to create a simple React component to achieve this:

    "use client";
    import React, { useState } from "react";
    
    function Input() {
      const [inputValue, setInputValue] = useState("");
      const [errorMessage, setErrorMessage] = useState("");
      const handleChange = (event: any) => {
        const value = event.target.value;
        setInputValue(value);
        if (/^-?d+$/.test(value)) {
          const intValue = parseInt(value);
    
          if (intValue >= -99 && intValue <= 99) {
            setErrorMessage("");
          } else {
            setErrorMessage("Please enter a number between -99 and 99.");
          }
        } else {
          setErrorMessage("");
        }
      };
      return (
        <>
          <input type="text" value={inputValue} onChange={handleChange} />
          <p style={{ color: "red" }}>{errorMessage}</p>
        </>
      );
    }
    
    export default Input;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search