I have a component that looks like this:
<input class="number-input py-1 primary--text font-weight-regular"
:ref="'number-input-' + title"
@keypress="onKeyPressed"
:disabled="disabled"
type="number"
v-model="result"
:min="minimum"
:max="maximum"
/>
import { Component, Prop, Vue } from 'vue-property-decorator'
import { floatFixedNumber } from '@/common/utils'
@Component({
name: 'NumberInput'
})
export default class NumberInput extends Vue {
@Prop({ type: String }) title!: string | null
@Prop({ type: Number }) value!: number
@Prop({ type: Boolean, default: false }) focused!: boolean
@Prop({ type: Number, default: 0 }) minAllowed!: number
@Prop({ type: Number, default: 999 }) maxAllowed!: number
@Prop({ type: Boolean, default: false }) disabled!: boolean
get result (): number {
return this.validateValue(this.value)
}
set result (value: number) {
if (!this.disabled) {
this.$emit('on-change', this.validateValue(value))
}
}
get minimum (): number {
return this.minAllowed === null ? 0 : this.minAllowed
}
get maximum (): number {
return this.maxAllowed === null ? 999 : this.maxAllowed
}
onKeyPressed () {
this.$nextTick(() => {
this.$forceUpdate()
})
}
validateValue (value: string | number | null): number {
value = Number(value)
value = isNaN(value) ? 0 : value
value = value < this.minimum ? this.minimum : value > this.maximum ? this.maximum : value
return floatFixedNumber(value)
}
mounted () {
if (this.focused && this.$refs['number-input-' + this.title]) {
(this.$refs['number-input-' + this.title] as HTMLElement).focus()
}
}
}
My goal is to limit the maximum allowed number to 999. However, even though I have set the max number to 999, users can still type 9999 into the input field.
I have already tried the following approaches:
get result (): number {
const num = this.validateValue(this.value) > this.maximum ? this.maximum : this.validateValue(this.value)
return num
}
onKeyPressed (event:any) {
const val = this.validateValue(event?.target.value)
if (val > this.maximum) {
this.result = this.maximum
} else {
this.$nextTick(() => {
this.$forceUpdate()
})
}
}
And another approach:
onKeyPressed (event:any) {
const val = this.validateValue(event?.target.value)
if (val > this.maximum) {
(this.$refs['number-input-' + this.title] as HTMLInputElement).value = this.maximum.toString()
} else {
this.$nextTick(() => {
this.$forceUpdate()
})
}
}
Despite trying these solutions, users are still able to input 9999 in the field even though the maximum allowed number is set to 999. Is there a way to prevent this and limit input to a maximum of 999?