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
});
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);
}
};
3
Answers
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, useinput type="text"
and add JavaScript validation to restrict input to numbers and enforce desired formatting rules.Html
JavaScript
I’ve tried this same thing in my one of the project…
.
I’ve tried this one
https://codesandbox.io/s/modest-taussig-kn49h2?file=/src/App.js
this will help you