/^(?!00)(?!\.)[0-9]*\.?[0-9]*$/ только цифры и точка, не может начинаться с 00 или . export const useNumericInput = () => { const [value, setValue] = useState<string>('') const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { const rgx = /^[0-9]*\.?[0-9]*$/ const inputValue = e.target.value if (!inputValue.match(rgx) || inputValue.charAt(0) === '.' || inputValue.charAt(1) === '0') { return setValue(prevState => prevState) } return setValue(inputValue) }; return { onChange, value } }; /// ИЛИ чистый js export const numericInputValidator = (e: React.ChangeEvent<HTMLInputElement>, inputId: string) => { const userInput = e.target.value // @ts-ignore const input: HTMLInputElement = document.getElementById(inputId) if (userInput.charAt(1) === '0') { input.value = '0' } if (userInput.charAt(0) === '.') { input.value = '' } input.value = input.value.replace(/[^0-9\.]/g,''); input.addEventListener("blur", () => { input.value = stringTrim(userInput, 10); }); input.addEventListener("focus", () => { input.value = userInput }) };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter