Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Component and Invalid Input

I have the following react component:

var App = React.createClass({
    getInitialState: function() {
        return {value: 4.5}
    },
    change: function(event) {
        this.setState({value: parseFloat(event.target.value)});
    },
    render: function() {
        return <input type="number" value={this.state.value} onChange={this.change}/>;
    }
});

React.render(<App/>, document.body);

You can see it here: http://jsfiddle.net/2hauj2qg/

The problem is that if I want to type in a number like: "4.7". When the user enters, "4.", it becomes "4", due to being converted to a float in back. But this interrupts what the user was typing. What's the recommended way of solving this problem?

like image 678
Winston Ewert Avatar asked Nov 23 '25 07:11

Winston Ewert


1 Answers

As imjared mentioned, it's because you're using parseFloat

this.setState({value: parseFloat(event.target.value)});

Instead, you may wish to only allow digits and the decimal. It stays stored as a string and never changes their input, but they're prevented from typing things like letters and spaces.

var nonNumericRegex = /[^0-9.]+/g;

this.setState({value: event.target.value.replace(nonNumericRegex, "")});

To allow negative numbers you need to do this:

this.setState({
    value: event.target.value
        .replace(nonNumericRegex, "")
        .replace(/^(-.*?)-/g, "$1")
});

To enforce a leading dollar sign and no more than two decimals, and if the first character (after the $) is the decimal, prefix it with 0.

this.setState({
    value: "$" + event.target.value
        .replace(nonNumericRegex, "")
        .replace(/(\.\d\d)\d+/g, "$1")
        .replace(/^\./g, "0.")
})
like image 65
Brigand Avatar answered Nov 25 '25 22:11

Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!