Reputation: 113
I am doing a decimal number input validation where I want to prevent typing 'point' for the second consecutive time
Above in the input box after keypress of the first period, I shouldn't be able to keypress it for the second consecutive time.
I have done this so far-
if (e.which === 190) {
if(value === '') {
e.preventDefault()
this.setState({[error]: "Only one period allowed in decimal numbers!"});
return false;
}
}
But this only prevents the 3rd keypress and allows the second period.
How do I prevent the keypress using JavaScript?
PS- I am using input field if type- 'number'. So the after I press the second dot the e.target.value becomes null.
Upvotes: 0
Views: 542
Reputation: 11257
Even if it passes the second decimal number issue, it will still allow alphabets inside the input field. Instead you could use:-
var textBox = document.getElementById("txt")
textBox.addEventListener("keyup",function(e) {
var floatValue = parseFloat(textBox.value) || ""
if(floatValue !== textBox.value) textBox.value = floatValue
})
Upvotes: 0
Reputation: 15290
You can use regular expression alongwith onChange
event.
testHanlder = (event) => {
let value = event.target.value;
if (value) {
value = value.replace(/\.+/g, ".")
this.setState({value})
}
}
Upvotes: 2