I am trying to replace "comma" with a "dot" in input type "Text". Currently in my code I am restricting my pattern "^([0-9]*[.])?[0-9]*$"
but I would like to allow user to type "comma" ( ,
) but replace automatically with "period" ( .
)
<input
type="text"
ref="double"
pattern="^([0-9]*[.])?[0-9]*$"
onKeyUp={this.validateKeyEvents.bind(this)}
value={this.state.value}
onChange={this.inputChanged.bind(this)}
/>
validateKeyEvents(event){
console.log("event occured" + event.charCode);
var keyVal = event.charCode;
if(keyVal == 188)
{
console.log("comma");
event.preventDefault();
var UserInput = ReactDOM.findDOMNode(this.refs.double).value;
UserInput = UserInput.replace(/,/g, ".");
return true;
}
else if(keyVal == 8 || keyVal == 46)
return true;
else if(keyVal == 0)
return true;
else if (keyVal == 9 || keyVal == 13 || keyVal == 110 || keyVal == 190)
return true;
else if(keyVal >=48 || keyVal <= 57)
return true;
else if(keyVal >= 96 || keyVal <= 105)
return true;
else if(keyVal >=35 || keyVal <=40)
return true;
else
return false;
}
inputChanged(event) {
var value = event.target.validity.valid
? event.target.value
: this.state.value;
this.setState(
{
value: value
});
}
You could simply pass the replaced string as a value for the input
:
<input
value={this.state.value.replace('.', ',')}
onChange={e => this.setState({value: e.target.value})} ... />
And just change your pattern to use a comma instead of a dot.
pattern="^([0-9]*[,])?[0-9]*$"
So i did the following changes:
in validateKeyEvents i added
if(keyVal == 188)
{
return true;
}
and in input
<input
type="text"
pattern="^([0-9]*[.?,])?[0-9]*$"
onKeyUp={this.validateKeyEvents.bind(this)}
value={this.state.value.replace(',','.')}
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.