skip to Main Content

why input type number allow — as input.

I want to disable it.

also it allow several cases like

-12-12

-121-

23-323-

3

Answers


  1. The input type="number" behavior you described, where it allows multiple minus signs and unexpected input patterns, is due to browser inconsistencies. To prevent this, use input type="text" and add JavaScript validation to restrict input to numbers and enforce desired formatting rules.

    Html

    <input type="text" id="numericInput" pattern="-?d*.?d+" title="Please enter a valid number" />
    

    JavaScript

    const numericInput = document.getElementById('numericInput');
    
    numericInput.addEventListener('input', function() {
      this.value = this.value.replace(/[^0-9.-]/g, '');  // Remove non-numeric characters except minus and dot
      this.value = this.value.replace(/(..*)./g, '$1'); // Remove extra dots
      this.value = this.value.replace(/^-/g, '');         // Remove leading minus signs
      this.value = this.value.replace(/-+/g, '-');       // Replace multiple minus signs with a single minus
    });
    
    Login or Signup to reply.
  2. I’ve tried this same thing in my one of the project…

    const [inputValue, setInputValue] = useState('');
    
      const handleInputChange = (event) => {
        // Remove any leading or trailing whitespace
        const newValue = event.target.value.trim();
        
        // Validate the input using a regular expression
        const validInputPattern = /^-?d*$/; // This allows for optional negative sign and digits
        
        if (validInputPattern.test(newValue)) {
          setInputValue(newValue);
        }
      };
    

    .

        <div>
          <input
            type="number"
            value={inputValue}
            onChange={handleInputChange}
          />
        </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search