In this post, we are going to learn about, How to allow Positive numbers in Textbox React JS with example code. Sometimes we have to allow only positive values in the text, To achieve this we have to validate the Input value entered by the user in the below textbox Regular Expression and call its changeTxtValue event . If the value is evaluated to True as per the Regular expression, We will be Assigning the value to State using this.setState({txtValue: e.target.value}).
Class App extends React.Component{
constructor(){
super(props);
this.state = {
txtValue: ''
};
this.onChange = this.onChange.bind(this)
}
changeTxtValue=(e)=>{
const re = /^[0-9\b]+$/;
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({txtValue: e.target.value})
}
}
render(){
return <input value={this.state.txtValue} onChange={(e)=> this.changeTxtValue(e)}/>
}
2. How to allow only positive and negative numbers with 2 decimals Textbox
In this example, We have used the Regular expression that validates the value entered by the user into the textbox that contains numbers with a positive, negative, and decimal point, If the values is evaluated to True using the Regular Expression and else no value will assign to text as well as the state using this.setState.
This Text box allows only positive and negative numbers with 2 decimals.
Class App extends React.Component{
constructor(){
super(props);
this.state = {
txtValue: ''
};
this.onChange = this.onChange.bind(this)
}
changeTxtValue=(e)=>{
const re = /^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$/;
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({txtValue: e.target.value})
}
}
render(){
return <input value={this.state.txtValue} onChange={(e)=> this.changeTxtValue(e)}/>
}
3. How to allow only positive and negative numbers with 2 decimals Textbox
In case we have to allow only negative and positive numbers up to 6 decimals digits in Textbox then we can use the below Regular Expression. Let us understand the Regular Expression step by step.
- ^: Used at beginning of the string.
- -?: one or zero “-“
- \d* : 0 to infinite numbers
- \.? : 0 or 1 “.”
- \d{0,6} : from 0 to 6 numbers
- $: Used to End of string
Class App extends React.Component{
constructor(){
super(props);
this.state = {
txtValue: ''
};
this.onChange = this.onChange.bind(this)
}
changeTxtValue=(e)=>{
const re = /^-?\d*\.?\d{0,6}$/
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({txtValue: e.target.value})
}
}
render(){
return <input value={this.state.txtValue} onChange={(e)=> this.changeTxtValue(e)}/>
}