I'm having a problem when trying to allow only numbers (it could be with one dot and one decimal) and numbers must be between 0 and 10. Examples:
- 2 -> allowed
- 8.5 -> allowed
- 7.14 -> not allowed
- 7.1 -> allowed
- 10.1 -> not allowed
- 10 -> allowed
- 15.2 -> not allowed
First of all, here is a piece of code:
HTML:
<b-form-input
v-model="userDto.score"
@keypress="restrictScoreValue"
type="number"
min=0
max=10
/>
JavaScript:
restrictScoreValue($event) {
const keyCode = ($event.keyCode ? $event.keyCode : $event.which)
// only allow number and one dot
if ((keyCode < 48 || keyCode > 57) && (keyCode !== 46 || this.userDto.score.indexOf('.') !== -1)) { // 46 is dot
$event.preventDefault()
}
// restrict to 1 decimal place
if (this.userDto.score !== null && this.userDto.score.indexOf('.') > -1 && (this.userDto.score.split('.')[1].length > 0)) {
$event.preventDefault()
}
}
It works allowing only numbers and one decimal after the dot. But it doesn't work allowing only numbers between 0 and 10 (I can input a lot of numbers before the dot), and if I paste an incorrect score (example: 15.43) it allows.
How can I improve the code to fit the requirements?