Hi Developers,
Today we are going to learn How to Allow Only Numbers in Textbox React JS . While getting contact details from the customers sometimes they will type different data other than the mobile numbers to avoid this we should allow only numbers in the numbers section in the contact form . In React JS we are using the function to check whether the input is number or not and this function is called once when their is any change in the input field by using onChange .when there is a change in the input it calls the function using onChange and the function checks the input is numbers.
In this below code in the handleChange() in input field using the condition
/^[0-9\b]+$/
to check whether the given input is number format .
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = {
number: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const re = /^[0-9\b]+$/;
if (event.target.value === '' || re.test(event.target.value)) {
this.setState({number: event.target.value})
}
}
handleSubmit(event) {
console.log(this.state);
event.preventDefault();
}
render() {
return (
<div>
<h1>How to Allow Only Numbers in Textbox in React ITSolutionsGuides</h1>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.number}
onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
render(, document.getElementById('root'));
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides