The 'e' is the only letter that's accepted in a number field because it allows for exponents. You could use input type="text" but it doesn't give you the browser's native up and down arrows that type="number" does. And the pattern attribute validates on submission but doesn't stop someone from typing the 'e' in the first place. In REACT you can use this to completely block the 'e' key from being typed in a number input:
<input type="number" onKeyDown={ (evt) => evt.key === 'e' && evt.preventDefault() } />
Answer from Jeff C on Stack OverflowThe 'e' is the only letter that's accepted in a number field because it allows for exponents. You could use input type="text" but it doesn't give you the browser's native up and down arrows that type="number" does. And the pattern attribute validates on submission but doesn't stop someone from typing the 'e' in the first place. In REACT you can use this to completely block the 'e' key from being typed in a number input:
<input type="number" onKeyDown={ (evt) => evt.key === 'e' && evt.preventDefault() } />
Here is the best validation which I use.Any symbol which not a number we remove with replace method. Input type need to be text. In other cases, it can work unexpectedly.
const [val, setVal] = useState("");
return (
<div className="App">
<input
type="text"
value={val}
onChange={e => setVal(e.target.value.replace(/[^0-9]/g, ""))}
/>
</div>
);
Codesandbox demo.
If you not good with regexp alternatively you can use second variant.
// Outside of function
const exceptThisSymbols = ["e", "E", "+", "-", "."];
//..
return (
<div className="App">
<input
type="number"
onKeyDown={e => exceptThisSymbols.includes(e.key) && e.preventDefault()}
/>
</div>
);
Codesandbox demo.
React: How to prevent user from entering 'e', '+' and '-' for input type="number"
Only numbers. Input number in React - javascript
How to allow only numbers in textbox in reactjs? - Stack Overflow
reactjs - How to limit the text filed length with input type number in React JS and prevent entry of E,e, -, + etc - Stack Overflow
This should work:
const onNumberInputChange = useCallback(({ target: { value } }) => {
if(!/\d*/.test(value)) return
setFilteredValue(value);
setUnfilteredValue(value);
}, []); const onNumerInputKeyDown = (event) => {
if(event.key === "e") event.preventDefault();
}
And if you update your number input to use this function on keyDown we should be able to stop the user from inputing e aswell
const onNumerInputKeyDown = (event) => {
if(event.key === "e") event.preventDefault();
}
Here the user will be able to delete their input completely and the user is prevented from using e.
It looks to me like number type fields interpret the e as part of a valid number using e notation. For example, 1e3 is the same as 1 x 10^3 or 1000. It doesn't literally expand the number into the normal base 10 notation, but I guess when you end a number in e, it isn't a valid number.
By the way, entering a + also has the same effect as typing an e.
You can address this by updating your onNumberInputChange function to something like this:
const onNumberInputChange = useCallback(({ target: { value } }) => {
const updatedValue = (value === "") ? filteredValue.replace(/[^0-9]/g, '') : value;
setFilteredValue(updatedValue);
setUnfilteredValue(value);
}, [ filteredValue ]);
Edit: I added the regex replace to handle when an e is inserted between numerals
Simply way in React
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010
You need to define it as normal input (type='text') with pattern for numbers only:
<input type="text" pattern="[0-9]*"
onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
And then to compare the validity of input:
const financialGoal = (evt.target.validity.valid) ?
evt.target.value : this.state.financialGoal;
The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.
Basic idea is:
Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.
For that use this regex: /^[0-9\b]+$/;
onChange handler will be:
onChange(e){
const re = /^[0-9\b]+$/;
// if value is not blank, then test the regex
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({value: e.target.value})
}
}
Working example:
class App extends React.Component{
constructor(){
super();
this.state = {value: ''};
this.onChange = this.onChange.bind(this)
}
onChange(e){
const re = /^[0-9\b]+$/;
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({value: e.target.value})
}
}
render(){
return <input value={this.state.value} onChange={this.onChange}/>
}
}
ReactDOM.render(<App/>,document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
A simple solution, using hooks:
const [age, setAge] = useState();
const handleChange = (e) => {
const value = e.target.value.replace(/\D/g, "");
setAge(value);
};
return (
<div>
<input value={age} onChange={handleChange} />
</div>
);
Example: https://codesandbox.io/s/adoring-minsky-9sqvv
insert the following function in input type="number"
<input type = "number" maxLength = "5" onInput={this.maxLengthCheck} />React function
maxLengthCheck = (object) => { if (object.target.value.length > object.target.maxLength) { object.target.value = object.target.value.slice(0, object.target.maxLength) } }
isNaN() and Number can be combined to reject strings that don't evaluate to numbers.
See below for a practical example.
// Field.
class Field extends React.Component {
// State.
state = { value: '' }
// Render.
render = () => <input placeholder="Numbers only" value={this.state.value} onChange={this.handlechange}/>
// Handle Change.
handlechange = ({target: {value}}) => this.setState(state => value.length <= 6 && !isNaN(Number(value)) && {value} || state)
}
// Mount.
ReactDOM.render(<Field/>, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Hey guys, I am using react hook form and zod to manage forms. I want to know how to only accept numbers in a input[type=text]. Please Help
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
// 0 for null values
// 8 for backspace
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
Hi everyone,
I'm working with an input type of number and I'm trying to implement a logic where the input takes only numeric values and a max of 12 digits. I have added the type of number and max of 12 but it still not working. Using Reactjs
Here is a sample of my code...
{paymentForm.map((field, index) =>
field.control === FormControl.TEXT ? (
<TextInput
id={field.name}
key={index}
label={field.label}
placeholder={field.placeholder}
sx={field.customStyle || {}}
valid={
(!formik.errors[
field.name as keyof typeof formik.errors
] &&
formik.touched[
field.name as keyof typeof formik.errors
]) as boolean
}
mask={field.mask}
max={"3"}
maxLength={"3"}
{...formik.getFieldMeta(field.name)}
{...formik.getFieldProps(field.name)}
onChange={(e) => formik.setFieldValue(field.name, e)}
/>
) : null,
)}